Yii2 Restful. How can i receive data from 3 tables

I want to receive data like this:

categories
----category1
----category2
topProducts
----product1
--------photo1
--------photo2
----product2
--------photo1
--------photo2

I need get all categories and top x products. Each product has two photos.
How can i do this by using yii2 restful?
Thanks.

Upvotes: 0

Views: 52

Answers (1)

csminb
csminb

Reputation: 2382

the query shold look something like this

Category::find()
    ->with(['subcategories','topProducts', 'topProducts.images'])
    ->all();

you can use joinWith if you absolutely want a single query


if you retrieve your data with an ActiveController, you need to specify extraFields to the Category model. (here's a rest-specific usage example - rest of the guide should prove usefull as well)

Category model:

public function extraFields() {
    return ['subcategories', 'topProducts'];
}
// product relation
public function getTopProducts(){
    return $this->hasMany(Product::className(), ['category_id' => 'id'])
        // ->order()->where() // your criterias
        ->limit(10);
}
// subcategories
public function getChildren(){
    return $this->hasMany(Category::className(), ['id' => 'parent_id']);
}

Product model:

public function extraFields() {
    return ['iamges'];
}
public function getImages(){
    return $this->hasMany(Image::className(), ['product_id' => 'id'])
}

ps. since you haven't posed any code or table structure, all relations in my example are based on standard naiming convention

Upvotes: 1

Related Questions