【发布时间】:2016-07-12 10:39:20
【问题描述】:
我有类别(类别模型)。
每个类别都有子类别(通过类别模型字段parent_id)。
每个子类别都有产品(通过产品字段category_id)。
我需要为每个父类别获取最新添加的产品。理想情况下,它应该接受一个请求。或者尽可能少的请求。
我认为它应该通过关系工作,看起来像下面这样:
$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');
}
这段代码没有按预期工作。写得是否正确,我应该如何实现这种类型的任务?
【问题讨论】:
-
您可以在数据库中为您添加的每个产品添加时间戳列,通过使用时间戳您可以编写查询以获取结果
-
如果你有relation
category_table with product_table and firstImage,那么你可以使用product.firstImage,然后你可以添加条件。
标签: php activerecord yii2