best approach to search from pivot table using laravel

无人久伴 提交于 2019-12-12 01:21:48

问题


Searching from pivot table using laravel.

Here is my table structure:

Product
id
name

Categories
id
name

product_category (Pivot table)

id
category_id
product_id

//products can have multiple categories 

Product model:

public function categories(){
     return $this->belongsToMany(Category::class, 'product_category');
}

What is the best way to search all products by category id? Currently I am doing this way, and it seems not an efficient way:

//Controller
$categories = product_category::where('category_id',1)->get();

Now I have to loop through categories and then get Products and pass it to views? Any idea how to do this in an efficient way?


回答1:


For this you could use the whereHas() method:

$categoryId = 1;

$products = Product::whereHas('categories', function ($query) use($categoryId) {
    $query->where('id', $categoryId);
})->get();    

The above will return all products that are in the Category where the id is equal to $categoryId.




回答2:


You can eager load products for a given category. Try:

$category = Category::with('products')->where('category_id',1)->find(1);

When you do this, only 2 database queries will be executed: one for loading the category, and one for loading related products.

Then in your Blade view you can do:

@foreach($category->products as $product
    {{ $product->name }}
@endforeach


来源:https://stackoverflow.com/questions/54230841/best-approach-to-search-from-pivot-table-using-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!