2 years ago

belongsToMany, pivot table and multiple condition

Posted 2 years ago by FabCol

Hi All, I'm suffering. Not (yet a master at eloquent lol).

I have: One table: messageTopics One table: users A belongsToMany relation between both.

In table message_topic, I have a 'sender_id' field. Sender is unique, so it can be directly in this table. Receivers (which are indeed users) can be multiple. So 'belongsToMany' in a table called messageTopics_users, with fields topic_id and receiver_id.

My model: public function receiver() { return $this->belongsToMany(User::class, 'messageTopics_users', 'message_id' ,'receiver_id'); }

For a given "$userId = Auth::user()->id;" I'm trying to get:

  • ALL the messages he sent
  • ALL the messages he received

Everything is the sale $topics result. So it's two conditions, one in messageTopics table and one in the pivot table.

I tried many things... nothing works....

Any idea?

Thanks FAB

Please sign in or create an account to participate in this conversation.