php – 使用Yii框架在模型类中添加新字段

在表格中,我有列’描述’,其中包含商品描述.
我希望在CGridView列中包含’short_description’,它将包含前150个字符.

class Product extends CActiveRecord
{   
    /**
     * The followings are the available columns in table 'Product':
     * @var integer $id
     * @var integer $id_cat
     * @var string $title
     * @var string $description
     * @var timestamp $date
     */
    public $id;
    public $id_cat;
    public $title;
    public $description;
    public $date;
    public $short_description ;

    public function init()
    {
        $this->short_description = substr($this->description, 0, 150);     
    }

不幸的是,这段代码不起作用.

解决方法:

您需要覆盖模型类的afterFind函数并编写代码

$this-> short_description = substr($this-> description,0,150);

在afterFind函数中.

你需要做这样的事情

protected function afterFind()
{
    parent::afterFind();
    $this->short_description = substr($this->description, 0, 150);
}

相关文章

1、将Yii2.0advanced版中应用主体frontend或backend应用复制...
Yii2restfulAPI文档一、配置模块:1.Config/main.php:  2...
Yii在framework/i18n/data/%lang%.php文件中有很多翻译.这...
在Yii2中,官方的页面多语言解决方案有两个:方案1,使用Yii...
Yii2.0对数据库查询的一些简单的操作1234567891011121314151...
数据查询User::find()->all();此方法返回所有数据;User:...