[英]Laravel 8 | How to join two foreign keys on the same table
Fields 'to_user_id' and 'from_user_id' are two id that are on the users table, since they have different values how to join my model 'Message' with the users table字段'to_user_id'和'from_user_id'是 users 表上的两个 id,因为它们有不同的值如何将我的 model 'Message' 与 users 表连接
$my_inbox=Message::select('messages.*', 'users.name toUser', 'users.name as fromUser')
->join('users', 'users.id', '=', 'to_user_id.user_id')
->join('users', 'users.id', '=', 'from_user_id.user_id')
->get();
Use différent aliases to join same table.使用不同的别名来加入同一个表。 You see that selecting the same field is conflicting with what you want.
您会看到选择相同的字段与您想要的内容相冲突。
$my_inbox=Message::select('messages.*', 'receiver.name toUser', 'sender.name as fromUser')
->join('users as receiver', 'receiver.id', '=', 'to_user_id.user_id')
->join('users as sender', 'sender.id', '=', 'from_user_id.user_id')
->get();
Or if you had set the correct relation in the Message class and the user class或者,如果您在消息 class 和用户 class 中设置了正确的关系
$my_inbox = $loggedUser->receivedMessages()->with('sender')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.