简体   繁体   English

使用Laravel查询生成器联接3个表

[英]Join 3 tables using Laravel Query Builder

I am trying to implement a reshare action button on a message posting website that I am working on and output those reshared message along with the messages that users have posted recently. 我正在尝试在我正在处理的消息发布网站上实现转发操作按钮,并将这些转发的消息与用户最近发布的消息一起输出。

For the time being I have a USERS table and a MESSAGES table. 我暂时有一个USERS表和一个MESSAGES表。 And in order to retrieve recently posted messages I use the below query. 为了检索最近发布的消息,我使用以下查询。

return DB::table('messages')
->join('users', 'users.username', '=', 'messages.username')
->select('users.username as username','messages.id as id','messages.message as message', 'users.firstName as firstName','users.lastName as lastName') ->orderBy('messages.id', 'desc')
->paginate(20);

But now I have added a RESHARES table in which I store username of the person who reshared the message and the message_id . 但是现在我添加了一个RESHARES表,其中存储了转发消息和message_id的人的用户名 So what I really want to know is how do I join these tables and retrieve both reshared message and recently posted messages. 因此,我真正想知道的是如何联接这些表并检索转发的消息和最近发布的消息。

Please do post your answer in relartion to Laravel Query Builder . 请确实将您的答案发布到Laravel Query Builder

You can simply add another join to your query. 您可以简单地将另一个联接添加到查询中。

DB::table(...)
->join(table2...)
->join(table3...)
->select(...)
->paginate(...)

and query for the additional columns exactly as you do in your query right now. 并完全按照您现在在查询中的方式查询其他列。

As not every message might be reshared, you should consider using a left join for your reshares table. 由于并非所有邮件都可以转发,因此您应考虑在转发表中使用左联接。 You can do so by using 您可以使用

->leftJoin()

again, exactly the way you do right now. 再次,完全按照您现在的方式进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM