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 ?

950

Answer

Solution:

The following code should do the trick:

public function chats()
{
  return $this->hasMany('App\Chat','sender_id')->union($this->hasMany('App\Chat','receiver_id'));
}

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.

622

Answer

Solution:

You were very close.hasMany() accepts chainedwhere() andorWhere() calls, so I would make that query like this:

public function chats()
{
    return $this->hasMany('App\Chat')
        ->where('sender_id', \Auth::id())
        ->orWhere('receiver_id', \Auth::id());
}

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.

People are also looking for solutions to the problem: javascript - {Wordpress } Use Select Box instead of Default Dropdown for products with variables?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.