Reputation: 398
Here I have these tables
table 1 => shops
-------------
id | name
table 2 => menus
-------
id | name | category_id
table 3 (pivot table) => menu_shop
---------
id | menu_id | shop_id
table 4 => categories
----------
id | name
I want to get the menus and shops with specific category name then my query is here
$menus =Menu::with('shops')->leftJoin('categories','menus.category_id','=','categories.id') ->where('categories.name','=','Chinese') ->take(6)->get();
then I display in the blade
@foreach($menus as $chinesemenu)
<div class="col-md-6 col-sm-12">
<div class="menu">
<img src="{{ '/images/menus/'. $chinesemenu->image }}" class="menuimg">
<p class="menutitle">{{$chinesemenu->title}} - <span class="menuprice">{{$chinesemenu->price}} Ks</span>
<a data-id="{{$chinesemenu->id}}" data-name="{{$chinesemenu->title}}" data-toggle="modal" data-target="#modalEdit" class="homeorder" ><i class="mdi mdi-cart"></i> </a>
</p>
<p class='menudescription'>
{{$chinesemenu->description}}
</p>
<span class="menushop">
@foreach($chinesemenu->shops as $shop)
{{$shop->name}}
@endforeach
</span>
</div>
</div>
@endforeach
Everything is ok except I only get only one shop from {{$shop->name}} after joining with categories table but it has two shops.
But when I change the query to this
$menus =Menu::with('shops')->take(6)->get();
I got the right output. But I have to join with categories table. help!
Upvotes: 1
Views: 85
Reputation: 746
Make query like
$menus = Menu::with('shops', 'category')->whereHas('category', function ($query) {
return $query->where('name', '=', 'Chinese');
})->take(6)->get();
And you need relation in Menu
public function category()
{
return $this->belongsTo(Category::class)
}
Now you should get only menus with category named "Chinese". :)
Upvotes: 2