Sunday, April 2, 2017

Laravel - belongsToMany with multiple tables

I created 3 Database Tables:

users - id - username - ...

messages - id - title - message

messages_user - messages_id - user_id - receive_user_id

The fields in messages_user are set as foreign key to the according tables.

The function I want to archieve is: I want to get all messages of a user, be it the one he created himself or he just received.

Current status: I am able to get all messages a user created by using a inside my User-Model:

return $this->belongsToMany('App\Messages', 'messages_user');

My problem currently is that I'm not able to get the received messages as well with one query. I could start a second query, but I'm sure their is a way to archieve that in another way.

Is that possible and if, how? :)

Thanks in advance!



via Cody McCodeFace

Advertisement