简体   繁体   中英

yii additional model attribute and It's scope

I'm fetching lots of Order records from database and I wanted to add another field, which is column in related table (customers), to fetched records.

but this field wont get fetched directly since it's not part of Orders model.

so I added an attribute to the model to hold this extra attributte and did my selection like this:

    $criteria = new CDbCriteria();
    $criteria->join = 'INNER JOIN customers c ON t.idCustomer = c.idCustomer';
    $criteria->select = 't.* , c.CustomerName AS CustomerName'; // CustomerName is the added attribute

    $data = Orders::model()->findAll($criteria);
    var_dump($data); // in here CustomerName is fetched,
    $data = CJSON::encode($data); // but not here, its not even part of encoded string!

I need to encode it right away and I don't want to put afterFind() in my model (although I don't think it would get encoded),

Is there some part I don't understand? how can I achieve this?

You can't do that without modifing the CActiveRecord class. In Yii by default you can't use the magic setters and getters. When you create the instance of your model, only the database columns are added in the attributes list.

You can add the additional attributes by overriding getMetaData() in your Model file:

public function getMetaData(){
    $data = parent::getMetaData();
    $data->columns['CustomerName'] = array('name' => '...');
    return $data;
}

Try to use this feature of yii: http://www.yiiframework.com/doc/guide/1.1/en/database.arr . You can do it in this way: in class Order:

 public function relations() { return array( 'customer' => array( self::HAS_ONE, 'Customer', array('idCustomer' => 'idCustomer' ) ); 

}

where Customer is CActiveRecord of table customer. Then, for getting additional fields from table customer show next code:

 $order = Orders::model()->find(100500); $customeName = $order->customer->CustomerName; 

UPDATED

Or you can use query builder and result will be in array: less functionality, but more performance with less memory consuming

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM