Could I got relations like this?


(dkbomb) #1
class Customer extends \yii\db\ActiveRecord
{
    public function getIAllItems()
    {
        return $this
                ->hasMany(Order::className,['Customer_id' => 'id'] )
                ->joinWith('items');
    }
}
class Order extends \yii\db\ActiveRecord
{
    public function getItems()
        {
            return $this->hasMany(Item::className,['Order_id' => 'id'] );
        }
}

Hello every one . I am a newbie in Yii
I have three tables Customer Order Item, I want to get all Items then Could I coded like above?


(Alexander Makarov) #2

https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#multi-table-relations


(dkbomb) #3

Thank for your reply
Is it the only way to Chaining multiple tables using via() or can do that just like I coded above?


(Alexander Makarov) #4

via and https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#junction-table.

In your case you’re doing a join so SQL is likely formed correctly but you’re not instructing framework to actually use this joined data. This distinction was introduced because fetching the data into Active Record instances isn’t free performance-wise and sometimes you need a join for filtering purpose only.


(dkbomb) #5

I have try both way to get data then I find out the result data structure is kind of different .
The result data structure is generated by joinWith() inside the hasMany() or hasOne() is like nested structure then I can figure out the item where is it come from order but other way to use via() that the data structure is kind of like horizontal structure oder collection and item collection are on the same level in this situation I can’t clearly to find out the item where is it come from. so if I just want to get all relations data of some customer and I don’t need to filtering or modify data can I just using hasMany or hasOne with joinWith ?


(Alexander Makarov) #6

I see. Try it.


(dkbomb) #7

Sure. Thanks a lot