【问题标题】:Get latest record for each category in one request | Yii2在一个请求中获取每个类别的最新记录 | Yii2
【发布时间】: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');
}

这段代码没有按预期工作。写得是否正确,我应该如何实现这种类型的任务?

【问题讨论】:

  • 您可以在数据库中为您添加的每个产品添加时间戳列,通过使用时间戳您可以编写查询以获取结果
  • 如果你有relationcategory_table with product_table and firstImage,那么你可以使用product.firstImage,然后你可以添加条件。

标签: php activerecord yii2


【解决方案1】:

在您的 Category 模型中,您可以执行类似的操作。

public function latestProducts()
{
    return Product::find()->where(['category_id' => $this->id])->published()->with('firstImage')->orderBy('date_create DESC')->all();
}

在您的视图中,在循环每个类别时,调用此函数,如下所示。

$category->latestProducts(); // where $category is the current category in loop

【讨论】:

  • 然后我们在循环中有与类别一样多的请求。那不是合适的解决方案。我想以尽可能少的请求数做到这一点。
  • 好吧,你在最初的问题中没有提到这一点,所以对技术上正确的答案投反对票对于寻求帮助的人来说有点苛刻。
  • 是的,很抱歉。 12 小时限制解除后,我将取消投票。我不小心放了。对我的任务有什么想法吗?
  • 运行代码时得到的错误或数据究竟是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-05
  • 2018-11-22
  • 1970-01-01
  • 2020-05-29
  • 2016-11-26
相关资源
最近更新 更多