php - Custom hasMany Relation Laravel
238
public function chats()
{
return $this->hasMany('App\Chat','sender_id')->orWhere('receiver_id',\Auth::id());
}
My requirement is that i want to fetch messages that being sent or received by User. how i can do it ?
Answer
Solution:
The following code should do the trick:
This will return a relation that is a union of 2 queries - one that fetches chat messages where given user is the sender and another one where given user is the receiver.
You can now access user's chats with $user->chats.
Answer
Solution:
You were very close.
hasMany()
accepts chainedwhere()
andorWhere()
calls, so I would make that query like this:Once this is correctly set up, you can use
$users->chats
to access a list of chats that were sent from OR to the current user.