Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel返回与两个表匹配的数据_Php_Laravel - Fatal编程技术网

Php Laravel返回与两个表匹配的数据

Php Laravel返回与两个表匹配的数据,php,laravel,Php,Laravel,我有两张不同的表格,如下所示: 表:产品 id->1 姓名->铅笔 大小->大 表:颜色 id->2 颜色名称->红色 产品标识->1 这是我在控制器中的代码 $products= Product::where('active', 1); if ($request->has('size')) { $products->whereIn('size', $request->input('size')); } $products= $products->pagina

我有两张不同的表格,如下所示:

表:产品

id->1 姓名->铅笔 大小->大

表:颜色

id->2 颜色名称->红色 产品标识->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"));

结果按请求的大小值进行过滤。但是问题是颜色在不同的表中,如何正确查询颜色过滤器?谢谢。

你可以用雄辩的语言很好地完成它。因此,在产品模型类中添加以下方法:

public function colours()
{
    return $this->hasMany(Colour::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();
然后,只需重复使用$colors即可:

foreach($colours as $colour)
{
    // $colour->product; is what you are looking for.
} 
--编辑

Product::with('colours', function($query) use ($colour) { 
    $query->where('colour_name', $colour);
});

您是直接使用雄辩的模型还是查询生成器?到目前为止您尝试了什么?做一个简单的leftJoin产品:leftJoin'colors',colors.Product\u id',products.id'->get;对不起,我忘了写,请求颜色还有第二个参数。我不知道在查询中把请求放在哪里。我编辑了我的问题。谢谢你的回答。实际上,我应该按照下面的$products->开始颜色查询。我该怎么做呢?你建立关系的方式是,你说一种产品有多种颜色。所以,我想明确一点,这是你的期望吗?或者你想要一种颜色有很多种产品,比如两种产品可以有一种颜色?是的,你说得对,对不起,我问的问题不对。如果我编辑我的问题,你会再看一次吗?是的,我在这里:我也编辑了我的答案,所以看看这是否对你有所帮助。但是你必须在模型中添加我上面提到的方法,最后我做到了。谢谢你的回答。干杯
Product::with('colours', function($query) use ($colour) { 
    $query->where('colour_name', $colour);
});