Search code examples
sqllaraveleloquentinner-join

INNER JOIN on Eloquent result sets in Laravel


I want to find a match between a database result set of a user and result sets of friends. First I'm making a call to the database to get the ids of the user items:

$user_simp_items = Item::select('simp_id')->where('user_id', $user_id)->get(); 

Then I loop through the friends and make a call to get their item ids:

$friend_simp_items = Item::select('simp_id')->where('user_id', $friend_id)->get(); 

To find the matching ids I want to perform an INNER JOIN on the result sets. How do I do this in Laravel?

I'd like to do something like inner_join($user_simp_items, $friend_simp_items) and get the result set with only the matching items.


Solution

  • I used the toArray Eloquent method and then did an array_filter to get the intersecting elements.