【问题标题】:How to query pivot tables with multiple relationships with Laravel and Eloquent如何使用 Laravel 和 Eloquent 查询具有多个关系的数据透视表
【发布时间】:2015-06-25 15:19:38
【问题描述】:

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

【问题讨论】:

    标签: php mysql laravel eloquent


    【解决方案1】:

    如果我没看错,这就是你需要的

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

    【讨论】:

      猜你喜欢
      • 2014-12-07
      • 2023-02-05
      • 2018-11-11
      • 2015-06-24
      • 2020-08-22
      • 1970-01-01
      • 2015-09-30
      • 2019-01-29
      相关资源
      最近更新 更多