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

时间:2015-04-18 19:27:39

标签: php mysql laravel eloquent

在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         |                   |

我的conversation_user表是数据透视表。

考试问题:我尝试使用conversation_user数据透视表获取与登录用户相关的所有conversation_id,然后使用这些结果获取与该对话相关的最后一条消息以及标题谈话所涉及的工作。

在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

但是我无法弄清楚如何用Eloquent来实现这个目标!

我的关系如下:

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');

1 个答案:

答案 0 :(得分:0)

如果我理解正确,这就是你需要的

    $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;
    }