【发布时间】:2021-03-23 01:23:48
【问题描述】:
我正在使用 Laravel 5.8 构建电子商务网站,但遇到以下问题。我想从一个类别及其子类别中检索所有产品,但之后能够在我的代码中执行过滤查询。例如产品的价格限制和数量供应。
商店有类别,在同一张表中有子类别。 类别表(简体) - id|name|parent_id - 如果 parent_id != 0,则该类别被视为主类别的子类别。
产品可以属于多个类别,因此我使用的是多对多关系。 产品表(简体) - id|name... 产品类别表 - id|product_id|category_id
我的产品模型如下所示:
public function categories()
{
return $this->belongsToMany(
'App\CatalogCategory',
'catalog_product_categories',
'product_id',
'category_id'
);
}
还有我的类别模型:
public function allProducts()
{
return $this->belongsToMany(
'App\CatalogProduct',
'catalog_product_categories',
'category_id',
'product_id'
)
->where('is_active', 1)
->whereDate('active_from', '<=', Carbon::now('Europe/Sofia'))
->where(function ($query)
{
$query->whereDate('active_to', '>=', Carbon::now('Europe/Sofia'))
->orWhereNull('active_to');
})
->wherePivotIn('category_id', $this->allChildrenIds());;
}
目前这样做,返回一个空集合:
$category = CatalogCategory::find(3);
dd($category->allProducts);
【问题讨论】:
-
定义的关系被命名为
products,所以它应该被访问为$category->products;——不是allProducts不是吗 -
我的错,没有正确复制它。我已经编辑过了。
标签: php laravel eloquent eloquent-relationship