使用 laravel 从枢轴 table 搜索的最佳方法
best approach to search from pivot table using laravel
使用 laravel 从枢轴 table 搜索。
这是我的 table 结构:
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 搜索所有产品的最佳方法是什么?
目前我是这样做的,好像效率不高:
//Controller
$categories = product_category::where('category_id',1)->get();
现在我必须遍历类别然后获取产品并将其传递给视图?知道如何以有效的方式做到这一点吗?
您可以 eager load 给定类别的产品。尝试:
$category = Category::with('products')->where('category_id',1)->find(1);
执行此操作时,只会执行 2 个数据库查询:一个用于加载类别,一个用于加载相关产品。
然后在你的 Blade 视图中你可以做:
@foreach($category->products as $product
{{ $product->name }}
@endforeach
为此,您可以使用 whereHas() 方法:
$categoryId = 1;
$products = Product::whereHas('categories', function ($query) use($categoryId) {
$query->where('id', $categoryId);
})->get();
以上将 return id 等于 $categoryId
的类别中的所有产品。
您可以在控制器的方法中使用它。这仅在 $request->$query(search) 具有值时有效。然后在这里我们使用 wereHas 来获取模型和 with->() 使用的关系获取枢轴 table 值
->when($request->query('search'), function ($query)use($request) {
$q= $request->query('search');
return $query->whereHas('relation name', function (Builder $query) use ($q) {
$query->with('pivot table name.column name')
->where('pivot table name.column name', 'like', "%{$q}%")
});})
使用 laravel 从枢轴 table 搜索。
这是我的 table 结构:
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 搜索所有产品的最佳方法是什么? 目前我是这样做的,好像效率不高:
//Controller
$categories = product_category::where('category_id',1)->get();
现在我必须遍历类别然后获取产品并将其传递给视图?知道如何以有效的方式做到这一点吗?
您可以 eager load 给定类别的产品。尝试:
$category = Category::with('products')->where('category_id',1)->find(1);
执行此操作时,只会执行 2 个数据库查询:一个用于加载类别,一个用于加载相关产品。
然后在你的 Blade 视图中你可以做:
@foreach($category->products as $product
{{ $product->name }}
@endforeach
为此,您可以使用 whereHas() 方法:
$categoryId = 1;
$products = Product::whereHas('categories', function ($query) use($categoryId) {
$query->where('id', $categoryId);
})->get();
以上将 return id 等于 $categoryId
的类别中的所有产品。
您可以在控制器的方法中使用它。这仅在 $request->$query(search) 具有值时有效。然后在这里我们使用 wereHas 来获取模型和 with->() 使用的关系获取枢轴 table 值
->when($request->query('search'), function ($query)use($request) {
$q= $request->query('search');
return $query->whereHas('relation name', function (Builder $query) use ($q) {
$query->with('pivot table name.column name')
->where('pivot table name.column name', 'like', "%{$q}%")
});})