使用 Laravel 从数据透视表中搜索的最佳方法 [英] best approach to search from pivot table using laravel

查看:15
本文介绍了使用 Laravel 从数据透视表中搜索的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 laravel 从数据透视表中搜索.

Searching from pivot table using laravel.

这是我的表结构:

Product
id
name

Categories
id
name

product_category (Pivot table)

id
category_id
product_id

//products can have multiple categories 

产品型号:

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

按类别 ID 搜索所有产品的最佳方法是什么?目前我正在这样做,这似乎不是一种有效的方式:

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?

推荐答案

为此,您可以使用 whereHas() 方法:

For this you could use the whereHas() method:

$categoryId = 1;

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

以上将返回类别中 id 等于 $categoryId 的所有产品.

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

这篇关于使用 Laravel 从数据透视表中搜索的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆