简体   繁体   English

如何使用Laravel和Eloquent查询具有多个关系的数据透视表

[英]How to query pivot tables with multiple relationships with Laravel and Eloquent

In Laravel 5, I have a database with the following schema: 在Laravel 5中,我有一个具有以下架构的数据库:

| USERS    | JOBS  | CONVERSATIONS | MESSAGES        | CONVERSATION_USER |
| id       | id    | id            | id              | user_id           |
| username | title | job_id        | conversation_id | conversation_id   |
| password |       |               | user_id         |                   |
|          |       |               | message         |                   |

Where my conversation_user table is a pivot table. 我的对话用户表是数据透视表。

Exam Question: I'm trying to use the conversation_user pivot table to obtain all of the conversation_ids relating to the logged in user and then use those results to get the last message relating to that conversation as well as the title of the job the conversations relate to. 考试问题:我正在尝试使用session_user数据透视表获取与已登录用户有关的所有session_id,然后使用这些结果来获取与该对话有关的最后一条消息以及与对话有关的工作的标题至。

In SQL terms this equates to: 用SQL术语来说等于:

SELECT t1.message, t2.title FROM

(SELECT messages.`message`, messages.conversation_id FROM conversation_user
INNER JOIN messages ON conversation_user.conversation_id=messages.conversation_id
WHERE conversation_user.user_id=$user_id ORDER BY messages.id DESC) t1

INNER JOIN

(SELECT jobs.`title`, conversations.id FROM conversations INNER JOIN jobs ON
conversations.job_id=jobs.id) t2

ON t1.conversation_id=t2.id

However I cannot figure out how to achieve this with Eloquent! 但是我不知道如何用Eloquent实现这一目标!

My relationships are below: 我的关系如下:

User model:
$this->hasMany('job');
$this->hasMany('message');
$this->belongsToMany('conversation');

Job model:
$this->belongsTo('user');
$this->hasMany('conversation');
$this->hasManyThrough('message', 'conversation');

Conversation model:
$this->belongsTo('job');
$this->hasMany('message');
$this->belongsToMany('user');

Message model:
$this->belongsTo('user');
$this->belongsTo('conversation');

If I undestood correctly, this is what you need 如果我没有正确理解,这就是您需要的

    $user = User::find(Auth::id());
    foreach($user->conversations()->with('messages', 'job')->get() as $conversation)
    {
        echo $conversation->job->title;
        echo $conversation->messages->sortBy('id')->last()->message;
    }

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

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