2015-04-03 65 views
1

我想建立一个使用Laravel 5和使用雄辩ORM工作网站的消息传递系统。基本前提是有人发布了一份工作,人们可以通过消息回应该工作。 MySQL数据库的结构为这样:Laravel雄辩的关系和连接多个表

**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查询范围(我的口才模型对话表),其完成显示经过验证的用户参与的会话的任务:

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中传递特定作业的标题以及最后一封消息的前几个单词那是在对话中发出的?

回答

1

我很抱歉,如果我说明明显,但:

对话模型属于工作模式。当你已经拥有了谈话对象/ 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);