如何在YII中从Db中获取期间更改日期格式


How to change the format of date during fetching from Db in YII?

我在yii中使用rest api调用。

这是我的模型

class  User extends ActiveRecord
    {
    }

在控制器中,我通过以下代码从db获取数据

$person = (new 'yii'db'Query())
                ->select(['*'])
                ->from('person')
                ->all();

person表中有一个日期字段(例如:createdTime)。

现在我得到日期格式。我想在这里换长衣服。我可以在哪里更改/设置这个对象的模型

如果您不想使用model,您可以在简单的循环中更改它:

$results = (new 'yii'db'Query())
    ->select(['*']) // you can omit this, it's redundant
    ->from('person')
    ->all();
foreach ($results as $key => $result) {
    $results[$key]['created_at'] = ... // replace with new value;
}

但我强烈建议使用模型代替,然后你可以使用内置的ArrayHelper toArray()方法来处理属性值,甚至添加新属性/修改它们的名称。例子:

use app'models'User;
use yii'helpers'ArrayHelper;
...
$initialModels = User::find()->all();
$models = ArrayHelper::toArray($models, [
    'app'models'User' => [
        'created_at' => function ($model) {
            return ...; // Return new value here
        },
    ],
]);

更多信息见官方文档