定义Laravel在消息系统中的3个模型之间的雄辩关系 [英] Define Laravel Eloquent relations between 3 models in a messaging system
本文介绍了定义Laravel在消息系统中的3个模型之间的雄辩关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对话
------------
id
消息
--------
id
conversation_id
from_id
subject
message
from_timestamp
参与者
------------
conversation_id
user_id
last_read_timestamp
你能帮我描述这些模型之间的雄辩关系吗?我的意思是: http://laravel.com/docs/eloquent#relationships
解决方案
类对话扩展Eloquent
{
public function messages()
{
return $ this-> hasMany('Message');
}
public function Particip()
{
return $ this-> hasMany('Participant');
}
}
class消息扩展Eloquent
{
public function conversation()
{
return $ this-> ; belongsTo('Conversation');
public function from()
{
return $ this-> belongsTo('User','from_id');
}
}
class参与者扩展Eloquent
{
public function conversations()
{
return $ this-> ; belongsTo('Conversation');
}
public function user()
{
return $ this-> belongsTo('User');
}
}
//消息
foreach($ conversation->消息为$ message)
{
echo'From: '。$ message-> from-> username。< br />; //在这里猜测取决于你的用户模型。
echo'Subject:'。$ message-> subject。< br />;
echo'Message:'。$ message-> message。< br />;
echo'Timestamp:'。$ message-> from_timestamp。< br />;
echo'< hr />';
}
//参与者
foreach($ conversation->参与者为$参与者)
{
echo'User:'。$ participant- > user-> username;
}
I'm trying to create multi-participant messaging system. Here's the database design I'v found here: Messaging system database schema
Conversation
------------
id
Messages
--------
id
conversation_id
from_id
subject
message
from_timestamp
Participants
------------
conversation_id
user_id
last_read_timestamp
Could you help me to describe Eloquent relations between these models? I mean this: http://laravel.com/docs/eloquent#relationships
解决方案
class Conversation extends Eloquent
{
public function messages()
{
return $this->hasMany('Message');
}
public function participants()
{
return $this->hasMany('Participant');
}
}
class Message extends Eloquent
{
public function conversation()
{
return $this->belongsTo('Conversation');
}
public function from()
{
return $this->belongsTo('User', 'from_id');
}
}
class Participant extends Eloquent
{
public function conversations()
{
return $this->belongsTo('Conversation');
}
public function user()
{
return $this->belongsTo('User');
}
}
// Messages
foreach($conversation->messages as $message)
{
echo 'From: '.$message->from->username."<br />"; // Taking a guess here, depends on your user model.
echo 'Subject: '.$message->subject."<br />";
echo 'Message: '.$message->message."<br />";
echo 'Timestamp: '.$message->from_timestamp."<br />";
echo '<hr />';
}
// Participants
foreach($conversation->participants as $participant)
{
echo 'User: '.$participant->user->username;
}
这篇关于定义Laravel在消息系统中的3个模型之间的雄辩关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文