[英]Get latest record for each category in one request | Yii2
I have category (Category model). 我有类别(类别模型)。
Each category has child categories (via Category model field parent_id
). 每个类别都有子类别(通过类别模型字段parent_id
)。
Each child category has products (via Product field category_id
). 每个子类别都有产品(通过“产品”字段category_id
)。
I need to get the latest added product for each parent category. 我需要为每个父类别获取最新添加的产品。 And ideally it should take one request. 理想情况下,它应该接受一个请求。 Or as less requests as possible. 或尽可能少的请求。
I think it should work via relation and looks something like the following: 我认为它应该通过关系来工作,看起来类似于以下内容:
$areas = Category::find()
->parent()
->published()
->orderBy('position ASC')
->with('latestProduct')
->limit(8)
->asArray()
->all();
public function getLatestProduct()
{
return $this->hasOne(Product::className(), ['category_id' => 'id'])
->viaTable('category', ['parent_id' => 'id'])
->published()
->with('firstImage')
->orderBy('date_create DESC');
}
This piece of code doesn't work as expected. 这段代码无法按预期运行。 Is it written correctly and how I should implement this type of task? 它编写正确吗?我应该如何执行此类任务?
In your Category
model, you can do something like this. 在Category
模型中,您可以执行以下操作。
public function latestProducts()
{
return Product::find()->where(['category_id' => $this->id])->published()->with('firstImage')->orderBy('date_create DESC')->all();
}
In your view while looping for each category, call this function as shown below. 在您为每个类别循环时的视图中,如下所示调用此函数。
$category->latestProducts(); // where $category is the current category in loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.