Laravel Eloquent 关系和连接多个表

Laravel Eloquent relationships and connecting multiple tables

我正在尝试使用 Laravel 5 和 Eloquent ORM 为求职网站构建消息传递系统。基本前提是有人发布了职位,人们可以通过消息回复该职位。 MySQL 数据库的结构如下:

**users table**
id
username
password

**jobs table**
id
user_id (FK with id on Users table)
slug
title
description

**conversations table**
id
job_id (FK with id on Jobs table)

**messages table**
id
conversation_id (FK with conversations table)
user_id (FK with id on users table)
message
last_read

**conversation_user table**
conversation_id (FK with id on Conversation table)
user_id (FK with id on Users table)

当用户找到他们喜欢的工作时,他们可以向工作创建者发送消息,这将创建一个新的对话。然后使用新创建的对话 ID 传递给消息 table(连同消息文本本身),然后 conversation_user 数据透视表 table 更新为对话 ID 以及两个用户参与对话的人(即发布职位的人和发送消息的人)

我每个 table 都有一个模型,关系的总结是:

**Job.php**
HasMany - Conversation model
BelongsTo - User model

**Conversation.php**
BelongsTo - Job model
HasMany - Message model
BelongsToMany - User model

**Message.php**
BelongsTo - Conversation model
BelongsTo - User model

**User.php**
HasMany - Job model
HasMany - Message model
BelongsToMany - Conversation model

我在 Conversation.php(我的 Eloquent 对话模型 table)中设置了一个查询范围,它完成了显示经过身份验证的用户正在参与的对话的任务:

public function scopeParticipatingIn($query, $id)
{
    return $query->join('conversation_user', 'conversations.id', '=', 'conversation_user.conversation_id')
        ->where('conversation_user.user_id', $id)
        ->where('conversation_user.deleted_at', null)
        ->select('conversations.*')
        ->latest('updated_at');
}

并通过我的对话存储库,我将查询范围的结果传递到我的 MessagesController 中的视图,如下所示:

public function __construct(ConversationInterface $conversation)
{
    $this->middleware('auth');
    $this->conversation = $conversation;
}

public function index()
{
    $currentUser = Auth::id();

    $usersConversations = $this->conversation->ParticipatingIn($currentUser, 10);

    return view('messages.index')->with([
        'usersConversations' => $usersConversations
    ]);
}

作为参考,ConversationInterface 绑定到我的 ConversationsRepo:

public $conversation;
private $message;

function __construct(Model $conversation, MessageInterface $message)
{
    $this->conversation = $conversation;
    $this->message      = $message;
}

public function participatingIn($id, $paginate)
{
    return $this->conversation->ParticipatingIn($id)->paginate($paginate);
}

我的问题是,鉴于我拥有我认为正确的关系,我如何才能从 job_id 对话 table 以及前几个对话中传递特定职位的头衔对话中发送的最后一条消息的字词?

对不起,如果我说的很明显,但是:

会话模型属于作业模型。由于您已经有了对话 object/id,只需执行以下操作:

//Controller
$conversation = App\Conversation::find($id);
return view('your view', compact('conversation'));

//View
$conversation->job->title; //the conversation belongs to a job, so requesting the job will return an instance of the job model, which can be asked for the title.

您也可以在视图上使用它来获取消息中的第一个字符:

substr($conversation->messages->last()->message,0,desired lenght);