我正在尝试使用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');
}
通过我的Conversations Repository,我将查询范围的结果传递给我在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传递特定作业的标题,以及在最后一条消息中传递的最后几个字。会话?
答案 0 :(得分:1)
如果我说的是明显的话,我很抱歉,但是:
会话模型属于Job Model。由于你已经有了对话对象/ 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);