Need only 1 Result from Many to Many Relation Laravel

Viewed 47

I have 3 tables with Many to Many relation.

Table1: shops -> name, location_id

Table2: items

Pivot table: item_shop -> item_id, shop_id

A Shop can have multiple items on its store and a item can be in multiple shops.

What I want is to get items result with only 1 shop info located in an area.

My current query:

$query = Item::whereIn('items.id', $itemids);

$query->whereHas('shops', function($q) use($city_id){
       $q->where('shops.city_id', $city_id);
     });

            //======= SLOW query
$query->with(['shops' => function($q) use ($city_id){
         $q->where('shops.city_id', $city_id);
});
$items = $query->get();

This query works but its slow on with(), probably because it retrieves all shops within the area .($city_id) so then I need to use $item->shops->first()->name to get 1 shop. What I need only 1 shop result. I cant seem to find something like one to one relation with pivot. tables are already indexed. I am using Laravel 5.3 Any suggestion how to achive it?

1 Answers

Just change the way you write your query.

Assuming your many-to-many relationship is called items in your Shop model:

$shop = Shop::with('items')->where('city_id', $city_id)->first();

// do something with $shop which now contains items collection
Related