【问题标题】:How to query for get all products related a specific category in mysql database laravel [closed]如何在mysql数据库laravel中查询获取与特定类别相关的所有产品[关闭]
【发布时间】:2020-09-12 08:16:56
【问题描述】:

以下是我的分类表:

此产品类别表:

这是产品表:

我想按特定和单个类别获取产品并显示在滑块中,例如

  • 类别为电子的所有产品
  • 类别为服装的产品
  • 类别为移动设备的所有产品

我很困惑如何通过连接所有表来查询和获取数据。

有人可以帮帮我吗?

【问题讨论】:

标签: php mysql laravel


【解决方案1】:

你可以利用口才和关系。 在您的 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();

【讨论】:

  • 感谢您的帮助,我通过另一个技巧实现了这一目标...非常感谢
【解决方案2】:

您可以通过在模型中定义如下关系来实现它:

在你的产品模型中定义一个分类函数

 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 表是一个数据透视表,数据透视表需要遵循的规则很少:

  1. 数据透视表应该是两个表的单数名称,在您的情况下应该是 product_category 表
  2. 数据透视表命名约定应该是字母表,在您的情况下应该是 category_product
  3. 不需要在数据透视表中创建 id 和 timestamps 列
  4. 您实际上不需要为数据透视表创建模型

另外,不是规则,而是建议您的表格列应该是蛇形大小写,例如 category_id

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

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

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

【讨论】:

  • 感谢您的帮助,我通过另一个技巧实现了这一目标...非常感谢
猜你喜欢
  • 1970-01-01
  • 2020-01-23
  • 2019-12-22
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
相关资源
最近更新 更多