Laravel 4关系:消息传递系统 [英] Laravel 4 Relationship: messaging system
问题描述
我遵循了ehp用户的建议,以构建一个轻量级的消息传递系统:
I followed the suggestions from user ehp in order to build a lightweight messaging-system:
https://stackoverflow.com/a/18717864/1084315
Users: id | username
Messages: id | from | content
user_messages: user_id | message_id
class User extends Eloquent {
public function messages()
{
return $this->belongsToMany('Message');
}
public function sent_messages()
{
return $this->hasMany('Messages', 'from');
}
}
class Message extends Eloquent {
public function from()
{
return $this->belongsTo('User', 'from');
}
public function to()
{
return $this->belongsToMany('User');
}
}
我创建这样的消息:
User::find(2)->messages()->create(array('text'=>'this is a message from admin to someone', 'from'=>'1');
现在,我需要查找/获取从特定用户到特定用户的每条消息. 但是在此示例中,仅发件人" ID直接存储在邮件"表中.
Now I need to find / get every Message from a specific user to a specific user. But in this example only the 'from' IDs are stored in the 'messages' table directly.
我什至无法通过使用
User::find(1)->sent_messages()->get();
在一个用户和另一个用户之间收集消息的最佳实践是什么?
What are best practices for collecting messages between one and another user?
高度赞赏的任何帮助
推荐答案
首先,我认为有一个小错字:
First of all, I think there's a small typo:
public function sent_messages() {
return $this->hasMany('Messages', 'from');
}
这可能应该是:
public function sent_messages() {
return $this->hasMany('Message', 'from');
}
现在,如果您希望将所有消息从一个用户发送到另一个用户,那该怎么办?未经测试,但对to
关系施加约束应该可以解决问题.
Now, if you're looking to get all the messages sent from one user to another, what about this? Untested, but placing a constraint on the to
relationship should do the trick.
$messages_from_A_to_B = Message::where('from', $UserA->id)->whereHas('to', function($q) use ($UserB) {
$q->where('user_id', $UserB->id);
})->get();
在旁注中,我假设您特别要求一个用户可以向多个用户发送消息?否则,下面的表结构看起来会更容易:
On a side note, I'm assuming that you specifically require that a user can send a message to more than one user? Else the following table structure seems like it would be easier:
users: id
messages: from | to
然后您只需要:
class User extends Eloquent {
public function messages() {
return $this->hasMany('Message', 'to');
}
public function sent_messages() {
return $this->hasMany('Message', 'from');
}
}
class Message extends Eloquent {
public function from() {
return $this->belongsTo('User', 'from');
}
public function to() {
return $this->belongsTo('User', 'to');
}
}
$messages_from_A_to_B = Message::where('from', $UserA->id)->where('to', $UserB->id)->get();
这篇关于Laravel 4关系:消息传递系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!