【问题标题】:Yii virtual attribute and modelsYii 虚拟属性和模型
【发布时间】:2014-10-15 12:24:19
【问题描述】:

虚拟属性可以代表模型吗?我读过这个wiki,但没有找到答案。

编辑: 目的是让我的模型对用户更明确。

abstract class BaseDonnee{
    protected $info;

    public function representingColumn(){
        return 'info'; //Please, I'm not sure this is right
    }

    public function setInfo(){
        //I can set the attribute's value
        $this->info = Info::model()->find('a condition')->info;
    }

    public function getInfo(){
        return $this->info;
    }
}

编辑 2: 运行代码时,我会得到一个异常:

CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Nom de colonne non valide : 'info'..

我怎样才能继续它的工作?

【问题讨论】:

    标签: yii model virtual-attribute


    【解决方案1】:

    可以,但不会被dataprovider等自动填写

    class User
    {
    
        /**
         * @var Address
         */
        private $_address = null;
    
        public function getAddress()
        {
            return $this->_address;
        }
    
        public function setAddress(Address $address)
        {
            $this->_address = $address;
        }
    
    }
    

    然后就可以使用了:

    $user = new User;
    
    $user->address = new Address();
    
    var_dump($user->address->street); // Assuming class Address has street field
    

    【讨论】:

    • 我可以看到。但是在创建类似代码时,假设我的属性未找到,我可能会遇到异常:CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Nom de colonne non valide : 'info'.. 我想我需要用我的模板更新我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多