我有两个表'用户'和'频道'
表:用户
id name channel
1 user1 1,2,3
2 user2 2,3
3 user3 2
表:渠道
id channel_name
1 IT
2 CS
3 EC
我需要结果
name channel_name
user1 IT,CS,EC
user2 CS,EC
user3 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();
红颜莎娜
哈士奇WWW