Yii2 ArrayHelper :: toArray不能递归工作

All*_*ell 3 php arrays helper yii2

Yii2 ArrayHelper的helper方法toArray不会转换嵌套对象。

这是我的测试代码。

public function actionTest()
{
    $product = \common\models\Product::find()
        ->where(['id' => 5779])
        ->with('firstImage')
        ->one();

    $product = \yii\helpers\ArrayHelper::toArray($product);

    print_r($product);
}
Run Code Online (Sandbox Code Playgroud)

默认情况下启用递归属性。

公共静态数组toArray($ object,$ properties = [],$ recursive = true)

因此,这段代码应该可以正常工作,但不能正常工作。

动作将返回一个没有firstImage对象的一级数组。

我在这里做错了什么?

PS: 为测试目的简化了代码。我知道在这种情况下,可以简单地使用asArray()方法来获取数组中的AR记录。

soj*_*oju 5

您应该改用:

$product = \common\models\Product::find()
    ->where(['id' => 5779])
    ->with('firstImage')
    ->asArray()
    ->one();
Run Code Online (Sandbox Code Playgroud)

了解有关在数组中检索数据的更多信息。

如果您确实要使用toArray(),并且由于关系不是真正的属性或属性,则应仅使用第二个参数,例如:

$product = \yii\helpers\ArrayHelper::toArray($product, [
    'common\models\Product' => [
        // add needed properties here
        // ...
        'firstImage',
    ],
]);
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用的是REST,则可以extraFields()在模型中进行覆盖:

public function extraFields()
{
    return ['firstImage'];
}
Run Code Online (Sandbox Code Playgroud)

阅读有关REST字段的更多信息。