Yii2 ArrayHelper 的辅助方法 toArray 不转换嵌套对象。
这是我的测试代码。
public function actionTest()
{
$product = \common\models\Product::find()
->where(['id' => 5779])
->with('firstImage')
->one();
$product = \yii\helpers\ArrayHelper::toArray($product);
print_r($product);
}
默认情况下启用递归属性。
public static array toArray ( $object, $properties = [], $recursive = true)
所以这段代码应该可以正常工作,但实际上没有。
Action 返回没有 firstImage
对象的一级数组。
我做错了什么?
附言:
出于测试目的简化了代码。我知道在这种特定情况下,可以简单地使用 asArray()
方法来获取数组中的 AR 记录。
最佳答案
你应该改用这个:
$product = \common\models\Product::find()
->where(['id' => 5779])
->with('firstImage')
->asArray()
->one();
阅读更多关于 Retrieving Data in Arrays 的信息.
如果您真的想使用 toArray()
,并且由于关系并不是真正的特性或属性,您应该简单地使用第二个参数,例如:
$product = \yii\helpers\ArrayHelper::toArray($product, [
'common\models\Product' => [
// add needed properties here
// ...
'firstImage',
],
]);
或者,如果您使用的是 REST,则可以覆盖模型中的 extraFields()
:
public function extraFields()
{
return ['firstImage'];
}
阅读更多关于 REST fields 的信息.
关于php - Yii2 ArrayHelper::toArray 不能递归工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38100428/