我想得到谁是发送聊天的联系人id,或者是我用原生查询发送聊天给他,我可以得到结果,但当我在laravel中实现它很困难,这是我的原生查询
select * from `users` where `users`.`id` in (
select `to` from messages where `from` = 2 group by `to`
union
select `from` from messages where `to` = 2 group by `from`
)我发现困难的是如何在group by或group by之后使用具有相同列号的联合,我使用了merge,但结果是错误的,这是我在laravel中尝试的
$to = Message::select('to')->where('from',auth()->id())->groupBy('to')->get();
$from = Message::select('from')->where('to',auth()->id())->groupBy('from')->get();
$tofrom = $to->merge($from);
dd($tofrom);如果有人能帮上忙,请
发布于 2020-01-25 22:53:40
merge()是收集的方法。不是雄辩的生成器或查询生成器。
但是,它认为您想要在数组中查找user.id。
您可以将集合转换为数组:
$to = Message::where('from',auth()->id())->groupBy('to')->pluck('to');
$from = Message::where('to',auth()->id())->groupBy('from')->pluck('from');
$tofrom = $to->merge($from)->toarray();
User::whereIn('id', $tofrom)->get();发布于 2020-01-25 23:18:05
联合在the documentation中进行了描述。要实现您的特定要求,您可以执行以下操作:
$final = User::whereIn('id', function ($query) {
$from = Message::select('from')->where('from',auth()->id())->groupBy('from');
$query->from('messages')->where('to',auth()->id())->groupBy('to')->union($from);
})->get();免责声明:我没有实际测试过,但我认为它应该可以工作。
发布于 2020-01-26 16:54:26
哦,我终于得到答案了,这是代码
$contacts = User::select('users.id','users.name','users.email','users.profile_image')
->join('messages',function($join){
$join->on('users.id','messages.from');
$join->orOn('users.id','messages.to');
})
->where(function($query){
$query->where('messages.from',auth()->id())->orWhere('messages.to',auth()->id());
})
->groupBy('users.id','users.name','users.email','users.profile_image')
->get();https://stackoverflow.com/questions/59910306
复制相似问题