【发布时间】:2020-11-23 10:27:40
【问题描述】:
我有模型
Product
id
name
....
....
示例:
1 | Product A
2 | Product b
3 | Product c
Category
id
category
.....
示例:
1 | Books
2 | cds
3 | paper
ProductCategory
id
product_id
category_id
......
example:
1 | 1 | 1
2 | 1 | 2
3 | 2 | 3
我的模型是这样的:
产品型号
public function category()
{
return $this->hasMany('App\ProductCategory', 'product_id', 'id');
}
类别模型
public function product_category()
{
return $this->belongsTo('App\ProductCategory', 'category_id', 'id');
}
产品类别模型
public function category()
{
return $this->belongsTo('App\Category', 'category_id', 'id')->where('status', '=', 1);
}
我的查询是写 Laravel Eloquent 查询,其中产品类别是“cds”
$products = Product::with('category')
// ->where('category_id', $cid)
->inRandomOrder()
->paginate(20);
我想要属于微粒类别的产品。例如:图书类别的产品。
【问题讨论】:
-
所以您只想要具有 category_id 是特定值的类别的产品?为什么有 3 个模型呢?
-
因为一个产品可以有多个类别一对多的关系
标签: laravel join eloquent conditional-statements