Check out Staudenmeir's Merged Relationships package. You can create a merge view migration which will allow you to then define a merge relation on the User model using that database view
Oct 5, 2024
2
Level 3
Pivot table with same model, how to get the "other user"?
I have a pivot model that matches two users with "user_id" and "matched_user_id" columns. What I want to achieve is something like :
For example matches table has these values :
user_id | matched_user_id
1 | 2
3 | 1
4 | 1
When I run something like :
User::find(1)->matches
I want it to return a collection of users with the ids 2,3 and 4. So the user I'm calling it from can be on either side of the pivot table. I've been trying to solve this since 3 days now.
I tried something like this, but I'm facing an n+1 query problem with this :
$matches = Match::where('user_id', auth()->id())->orWhere('matched_user_id', auth()->id())->get();
foreach($matches as $match){
echo $match->user_id == auth()->id() ? User::find($match->matched_user_id)->name : User::find($match->user_id)->name;
}
and honestly it doesn't look clean at all. I hope there's a better and more efficient way to do this.
Level 104
1 like
Please or to participate in this conversation.