【问题标题】:Yii2 ArrayHelper::toArray doesn't work recursivelyYii2 ArrayHelper::toArray 不能递归工作
【发布时间】:2016-11-01 05:03:11
【问题描述】:

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

默认启用递归属性。

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

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

Action 返回没有firstImage 对象的一级数组。

我在这里做错了什么?

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

【问题讨论】:

    标签: php arrays yii2 helper


    【解决方案1】:

    你应该改用这个:

    $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的信息。

    【讨论】:

    • 我知道。出于测试目的,有意简化了代码。在一些更复杂的情况下,我需要将 AR 对象转换为数组。我需要它递归地工作。
    • 这样,需要添加所有模型属性,会比较长。有什么精确的方法可以做到这一点吗?这样所有模型及其相关模型都将进入数组。
    • @FSShaikh 不,据我了解,您应该明确指定要在输出数组中包含的属性。
    • 谢谢,但它会增加所有请求中的代码行数,基本上我必须开发 REST 应用程序,它将以 JSON 格式发送响应。
    • 你应该问另一个问题......或者简单地阅读这个:yiiframework.com/doc-2.0/guide-rest-resources.html#fields
    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2018-06-17
    • 2018-08-19
    • 2016-04-30
    • 1970-01-01
    • 1970-01-01
    • 2022-12-24
    相关资源
    最近更新 更多