我有两个表'用户'和'频道'表:用户id name channel1 user1 1,2,32 user2 2,33 user3 2表:渠道id channel_name1 IT2 CS3 EC我需要结果name channel_nameuser1 IT,CS,ECuser2 CS,ECuser3 CS使用 laravel 查询生成器如何编写查询?我在下面尝试过,但我将channel_name 设置为NULL。试试 1$UserChannelList = Users::select('users.name as username', DB::raw("(GROUP_CONCAT(channels.channel_name SEPARATOR ',')) as 'channel_name'")) ->leftjoin('channels', function ($join) { $join->whereRaw("FIND_IN_SET('channels.id', 'users.channel')"); }) ->groupBy('users.name') ->orderBy('users.name', 'ASC') ->get();试试 2$UserChannelList = Users::select('users.name as username', DB::raw("(GROUP_CONCAT(channel.channel_name SEPARATOR ',')) as 'channel_name'")) ->leftjoin('channel', function ($join) { $join->on(DB::raw("CONCAT(',', 'users.channel', ',')"), 'like', DB::raw("CONCAT(',','channel.id',',')")); }) ->groupBy('users.name') ->orderBy('users.name', 'ASC') ->get();
2 回答
哈士奇WWW
TA贡献1799条经验 获得超6个赞
这是您的解决方案,请检查
$UserChannelList = DB::table('users') ->select('users.name', DB::raw("(GROUP_CONCAT(channels.channel_name)) as 'channel_name'")) ->rightJoin('channels', function($join){ $join->whereRaw('FIND_IN_SET(channels.id, users.channel)'); }) ->groupBy('users.name') ->orderBy('users.name', 'ASC') ->get();
- 2 回答
- 0 关注
- 196 浏览
添加回答
举报
0/150
提交
取消