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_category表
  • 数据透视表命名约定应该是算术的,在您的情况下,它应该是category_产品
  • 不需要在ppivot表中创建id和timestamps列
  • 您实际上不需要为透视表创建模型
  • 此外,这不是一条规则,而是一条建议,表列应该是蛇形的,例如category_id

    在模型中定义这些函数后,您可以按如下方式访问相关数据:

    $product = Product::find(27); //finding product by id
    $product->categories;
    
    $category = Category::find(187); //finding category by id 
    $category->products;
    

    使用此处的关系请修复您的问题,图像未渲染感谢您的善意帮助我通过另一个技巧实现了这一点…非常感谢manthanks的善意帮助我通过另一个技巧实现了这一点…非常感谢