在 yii2 中使用 `with` 的嵌套关系

2022-01-07 00:00:00 php yii2

谁能告诉我,我有几个型号:一个Item有很多→属性,On Property有很多→特性我可以这样做:

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();

结果:

{
  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?

推荐答案

来自 Yii 使用数据库的指南:

您可以急切地加载深度嵌套的关系,例如 a.b.c.d.所有父关系都将被急切地加载.也就是说,当你使用 abcd 调用 with() 时,你会急切地加载 a, ab, >abcabcd.

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.

所以使用properties.characteristics:

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

相关文章