我有两个类似的表:
表:产品
id->1
name->pencil
siz->big
表:颜色
id->2
colour_name->red
product_id->1
这是我在控制器中的代码;
$products= Product::where('active', 1);
if ($request->has('size')) {
$products->whereIn('size', $request->input('size'));
}
$products= $products->paginate(10);
return view('pencil.index', compact("products"));
根据请求的大小值过滤结果。但是不同表中的颜色问题,如何正确查询滤色器?谢谢。
答案 0 :(得分:1)
您可以使用Eloquent很好地做到这一点。因此,请在您的Product
模型类中添加以下方法:
public function colours()
{
return $this->hasMany(Colour::class);
}
以及您的Colour
模型中:
public function product()
{
return $this->belongsTo(Product::class);
}
然后在您的控制器中或任何有业务逻辑的地方,您都可以这样做:
Product::where('id', $productId)->colours; // this gives you list of all the colours for that product.
获取基于颜色名称的颜色列表:
$colours = Colour::where(
'colour_name', request('colour')
)->get();
然后简单地在$colours
上进行迭代时,您可以使用:
foreach($colours as $colour)
{
// $colour->product; is what you are looking for.
}
---编辑
Product::with('colours', function($query) use ($colour) {
$query->where('colour_name', $colour);
});