Can I globally change the "updated_at" and "created_at" names?

In my database my date columns aren’t named “created_at” and “updated_at” but instead “dateCreated” and “dateUpdated”. Right now for every ActiveRecord I create I’m modifying this in the behaviors() function like this:


    public function behaviors()

    {

        return [

            [

                'class' => TimestampBehavior::className(),

                'value' => new Expression('NOW()'),

                'attributes' => [

                    ActiveRecord::EVENT_BEFORE_INSERT => ['dateCreated', 'dateUpdated'],

                    ActiveRecord::EVENT_BEFORE_UPDATE => ['dateUpdated'],

                    ActiveRecord::EVENT_BEFORE_DELETE => ['dateDeleted'],

                ],

            ],

        ];

    }

Is there any way I can change this globally for the ActiveRecords so I don’t have to add this piece of code for all my models?

If they’re not configurable anywhere, you can just extend the AR class, and have your models extend your own class rather than Yii’s core AR class.

i.e. something like this (untested, but the basic philosophy stands)




<?php


namespace app\components;


use yii\helpers\ArrayHelper;


class ActiveRecord extends \yii\db\ActiveRecord

{

    public function behaviors()

    {

        return ArrayHelper::merge(parent::behaviors(), [

            [

                'attributes' => [

                    ActiveRecord::EVENT_BEFORE_INSERT => ['dateCreated', 'dateUpdated'],

                    ActiveRecord::EVENT_BEFORE_UPDATE => ['dateUpdated'],

                    ActiveRecord::EVENT_BEFORE_DELETE => ['dateDeleted'],

                ],

            ],

        ]);

    }

}


<?php


namespace app\models;


use app\components\ActiveRecord;


class BlogPost extends ActiveRecord

{

    ...

}

Otherwise just search the codebase for references to created_at (grep -r ‘created_at’ /path/to/yii) and see if they’re hardcoded or pulling from a specific location.

Ah yes, perfect. Thank you :)