$category=Category::all();
$product=Product::all()->where('category_id',$category->name)->get();
从名称中更改类别ID 将一张表连在一起5.5中
答案 0 :(得分:3)
请参阅有关建立关系的Laravel文档:
https://laravel.com/docs/5.5/eloquent-relationships
Category
&之间的关系Product
是一对多,所以它将是:
// app/Category.php
public function products()
{
return $this->hasMany(Product::class);
}
答案 1 :(得分:0)
您需要返回一个视图并传递数据,而不是返回一个集合:
return view('some.view', [
$category => Category::all();
$product => Product::where('category_id', $category->name)->get();
]);
https://laravel.com/docs/5.5/views#passing-data-to-views
此外,当你这样做时:
$product=Product::all()->where('category_id',$category->name)->get();
您正在将所有产品从DB加载到内存中,然后过滤它们,因为all()
正在执行查询。不要这样做。