Yii2 ArrayHelper::toArray 不能递归工作
Yii2 ArrayHelper::toArray doesn't work recursively
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)
所以这段代码应该可以正常工作,但实际上没有。
动作returns一级数组,无firstImage
对象。
我哪里做错了?
PS:
出于测试目的简化了代码。我知道在这种特定情况下,可以简单地使用 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。
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)
所以这段代码应该可以正常工作,但实际上没有。
动作returns一级数组,无firstImage
对象。
我哪里做错了?
PS:
出于测试目的简化了代码。我知道在这种特定情况下,可以简单地使用 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。