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将其传递到消息表(与消息文本本身一起),然后使用会话id以及参与会话的两个用户(即发布作业的人和发送消息的人)更新conversation_user透视表

我为每个表格都有一个模型,关系摘要如下:

**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(Conversations表的Eloquent模型)中设置了一个查询范围,它完成了显示经过身份验证的用户正在参与的对话的任务:

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

通过我的ConversationsRepository,我将查询范围的结果传递到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以我的ConversationRepo:为界

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传递特定工作的标题,以及在对话中发送的最后一条消息的前几个字?

如果我说的是显而易见的,我很抱歉,但是:

会话模型属于工作模型。既然你已经有了对话对象/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);