Nested relations using `with` in yii2

2019-02-19 06:47发布

问题:

Can someone tell me, I have several model: One Item has many → Properties, On Property has many → Characteristics I can do like this:

return Item::find()->where(['code' => $code])->with('properties')->asArray()->one();

result:

{
  title: "Ванна чугунная Ностальжи 150 с ножками",
  new: "0",
  hit: "0",
  recommend: "0",
  properties: [
  {
    //lallala
  },
  {
    //lallala
  },
  ]
}

But i want nested rows (Characteristics) in every property how can i do that much elegant way?

回答1:

From the Yii guide on working with databases:

You can eagerly load deeply nested relations, such as a.b.c.d. All parent relations will be eagerly loaded. That is, when you call with() using a.b.c.d, you will eagerly load a, a.b, a.b.c and a.b.c.d.

So use properties.characteristics:

return Item::find()->where(['code' => $code])->with('properties.characteristics')->asArray()->one()


标签: php yii2