Laravel 4 Relationship: messaging system

核能气质少年 提交于 2019-12-07 02:38:31

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