向不在数据库中的yii2活动记录模型添加属性 [英] Adding an attribute to yii2 active record model that is not in database

查看:172
本文介绍了向不在数据库中的yii2活动记录模型添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mySQL数据库,该数据库具有表视频和两列 start_time end_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('Ym-d');
return $日期;
},
],
],
'响应'=> true,
'hover'=> true
]); ?>

但是这并不理想,因为我希望能够利用日期和时间作为属性在我的videoSearch模型中进行过滤和排序。



根据我的研究,我在rule()和但是attributeLabel()函数不确定如何设置该值。我最初的想法是像做一个关系...

 公共函数getVideodate(){
$ datetime =新的DateTime('start_time');
$ date = $ datetime-> format(’Y-m-d’);
返回$ date;
}

但是,这不能产生预期的结果。我想出是否可以在模型中定义和设置它,然后将其添加到搜索模型中应该很简单,因为我的临时解决方案(在视图中)使这变得很复杂。



我打算在他改进的gridview小部件上使用kartik的日期范围和时间过滤器。

尼克

解决方案

在模型中定义虚拟变量

  class Video扩展\yii\db\ActiveRecord {

公共$ video_date; //定义虚拟属性
public $ video_time; //定义虚拟属性

公共功能rules()
{
return [
//其他规则...
[['video_date', 'video_time'],'safe'],
];
}

//使用Video :: find()
//您可以在此处设置虚拟属性的值,例如
公共函数afterFind()
{
parent :: afterFind();

$ datetime = new DateTime(’start_time’);

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

//在将记录插入数据库
//在模型
上调用save()之后,将立即调用此方法$ Save($ insert)
{
if(parent :: beforeSave($ insert)){
if($ insert){
//如果新记录已插入db
} else {
//如果现有记录已更新
//您可以使用类似
//的方式来防止更新某些数据
// $ this-> status = $ this- > oldAttributes ['status'];
}

$ this-> start_time = $ this-> video_date。 ’’。 $ this-> video_time;

返回true;
}

返回false;
}

}

在视图中,然后使用video_date / video_time作为属性,您也可能希望添加属性标签以进行建模。


I have a mySQL database that has a table videos and two columns, start_time and end_time, which are in the format 2017-01-24 15:38:11.

I have an active record model Videos that extends \yii\db\ActiveRecord and i would like to add a few additional attribute that are not in the database.

I am trying to split the time stamp into a separate date and time that i can then display as columns in my gridview widget. I successfully did this by setting the column values directly in the view to functions with something like this...

<?= 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
]); ?>

However this is less than ideal as i would like to be able to utilize the date and time as attributes in my videoSearch model for filtering and sorting.

From my research i have added the attribute to the Video model in both my rules() and attributeLabel() functions however am unsure of how to set the value. My initial thought was to do it like a relation...

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

However this does not yield the desired results. I figured if i can get it defined and set in the model then adding it to the search model should be simple were as my temporary solution (in the view) complicated this significantly.

I intend to use kartik's daterange and time filters on his improved gridview widget. Thanks ahead and please let me know what else i can include.

Nick

解决方案

In your model define virtual variables

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

}

In view you then use video_date / video_time as attribute, also you might want to add attribute labels to model too.

这篇关于向不在数据库中的yii2活动记录模型添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆