Laravel ORM is a lot for many relationships with key conditions
I have a table members
like this:
------------------
| id | name | ...
------------------
1 John
2 Jane
3 Bill
and a relations
to preserve their relationship.
----------------------------
| from_id | to_id | status |
----------------------------
1 2 friend
2 3 friend
the first entries say: member # 1 and member # 2 are friends.
member#1 is friend with #2
And member#2 is friend with #1
.
in Laravel, How can I have a relationship to get all the friends of a member?
I need to check both columns from_id
and to_id
, and with this syntax in my model, Member
I cannot get it.
Participant model
public function friends(){
return $this->belongsToMany('Member', 'relations', 'from_id', 'to_id' );
}
this only returns records that member_id from_id
I want to get this request if member = 1
SELECT * FROM relations WHERE from_id = 1 OR to_id = 1
any help?
thank.
source to share
Well this is the wrong answer to my question using Laravel ORM, but I am using this and it gives the same result. Hopefully if anyone else knows the correct answer, please share us here. thank.
Define this method in the Member
model:
return Member::join('relations', function($join) use($limit) {
$join->on('relations.from_id', '=', 'members.id')
->orOn('relations.to_id', '=', 'members.id');
})
->where(function($where){
$where->where('relations.from_id', '=', $this->id)
->orWhere('relations.to_id', '=', $this->id);
})
->where('members.id', '!=', $this->id)
->groupBy('members.id')
->get();
So I can use:
$member = Member::find(1); // for example user#1
$member->friends(); // a list of eloquent objects of members.
source to share