将属性添加到不在数据库中的yii2活动记录模型

Nic*_*k R 3 php activerecord yii2

我有一个mySQL数据库,有一个表视频和两列,start_timeend_time,格式为2017-01-24 15:38:11.

我有一个活动的记录模型视频扩展\ yii\db\ActiveRecord,我想添加一些不在数据库中的其他属性.

我试图将时间戳分成一个单独的日期和时间,然后我可以在gridview小部件中显示为列.我通过在视图中直接将列值设置为具有类似内容的函数来成功完成此操作...

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel'  => $searchModel,
    'columns' => 
    [
        [
        'class' => '\kartik\grid\DataColumn',
        'attribute' => 'videodate',
        'value' =>  function($model)
            {
                $datetime = new DateTime('start_time');
                $date = $datetime->format('Y-m-d');
                return $date;
            },
        ],  
    ],
    'responsive'=>true,
    'hover'=>true
]); ?>
Run Code Online (Sandbox Code Playgroud)

然而,这并不理想,因为我希望能够将我的videoSearch模型中的日期和时间用作属性进行过滤和排序.

根据我的研究,我已经在我的rules()和attributeLabel()函数中将属性添加到视频模型中,但是我不确定如何设置值.我最初的想法是像关系那样做...

public function getVideodate(){
    $datetime = new DateTime('start_time');
    $date = $datetime->format('Y-m-d');
    return $date;
}
Run Code Online (Sandbox Code Playgroud)

然而,这不会产生期望的结果.我想如果我可以在模型中定义并设置然后将其添加到搜索模型应该是简单的,因为我的临时解决方案(在视图中)显着复杂化.

我打算在他改进的gridview小部件上使用kartik的日期范围和时间过滤器.在此,谢谢你,让我知道我还能包括什么.

缺口

Rip*_*per 7

在您的模型中定义虚拟变量

class Video extends \yii\db\ActiveRecord {

    public $video_date; // defining virtual attribute
    public $video_time; // defining virtual attribute

    public function rules()
    {
        return [
            // other rules ...
            [['video_date', 'video_time'], 'safe'],
        ];
    }

    // this method is called after using Video::find()
    // you can set values for your virtual attributes here for example
    public function afterFind()
    {
        parent::afterFind();

        $datetime = new DateTime('start_time');

        $this->video_date = $datetime->format('Y-m-d');
        $this->video_time = $datetime->format('H:i:s');
    }

    // this method is called right before inserting record to DB
    // after calling save() on model
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($insert) {
                // if new record is inserted into db
            } else {
                // if existing record is updated
                // you can use something like this 
                // to prevent updating certain data
                // $this->status = $this->oldAttributes['status'];
            }

            $this->start_time = $this->video_date . ' '. $this->video_time;

            return true;
        }

        return false;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用video_date/video_time作为属性,也可以将属性标签添加到模型中.