Laravel 4 Relationship: messaging system

六眼飞鱼酱① 提交于 2019-12-08 06:01:17

问题


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

I create a message like this:

User::find(2)->messages()->create(array('text'=>'this is a message from admin to someone', 'from'=>'1');

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.

I can not even access the pivot of any Message by using

User::find(1)->sent_messages()->get();

What are best practices for collecting messages between one and another user?

Any help highly appreciated


回答1:


First of all, I think there's a small typo:

public function sent_messages() {
  return $this->hasMany('Messages', 'from');
}

This should probably be:

public function sent_messages() {
  return $this->hasMany('Message', 'from');
}

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

And then you just need:

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();


来源:https://stackoverflow.com/questions/25429229/laravel-4-relationship-messaging-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!