简体   繁体   中英

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 ).

Each child category has products (via Product field 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM