Php 如何在mysql数据库laravel中查询获取与特定类别相关的所有产品
以下是我的类别表: 这将显示产品类别表: 这是产品表: 我想通过特定的和单一的类别获得产品,并显示在滑块中,如Php 如何在mysql数据库laravel中查询获取与特定类别相关的所有产品,php,mysql,laravel,Php,Mysql,Laravel,以下是我的类别表: 这将显示产品类别表: 这是产品表: 我想通过特定的和单一的类别获得产品,并显示在滑块中,如 类别为电子产品的所有产品 类别为服装的产品 类别为移动的所有产品 我不知道如何通过连接所有表来查询和获取数据 有人能帮我吗?你可以利用雄辩的口才和这段关系。 在ProductCategory模型上,请执行以下操作: public function product(){ return $this->belongsTo('App\Product', 'productId'
- 类别为电子产品的所有产品
- 类别为服装的产品
- 类别为移动的所有产品
有人能帮我吗?你可以利用雄辩的口才和这段关系。 在ProductCategory模型上,请执行以下操作:
public function product(){
return $this->belongsTo('App\Product', 'productId')
}
public function category(){
return $this->belongsTo('App\Category', 'categoryID')
}
然后您可以这样查询:
ProductCategory::with(['product','category'])->where('categoryId', 191)->get();
您可以通过如下方式在模型中定义关系来实现:
$product = Product::find(27); //finding product by id
$product->categories;
$category = Category::find(187); //finding category by id
$category->products;
在产品模型中定义类别功能
public function categories() {
return $this->belongsToMany(Category::class, 'product_categories', 'productId', 'categoryId');
}
类似地,在类别模型中定义产品的关系
public function products() {
return $this->belongsToMany(Product::class, 'product_categories', 'categoryId', 'productId');
}
本例中的product_categories表是透视表,透视表遵循的规则很少:
$product = Product::find(27); //finding product by id
$product->categories;
$category = Category::find(187); //finding category by id
$category->products;
使用此处的关系请修复您的问题,图像未渲染感谢您的善意帮助我通过另一个技巧实现了这一点…非常感谢manthanks的善意帮助我通过另一个技巧实现了这一点…非常感谢