Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii CDbCriteria and Model->findAll, how to add custom column?

Tags:

php

yii

I have a calendar app in Yii where I store events per user. I'd like to dynamically build a title for each event.

This code is in my controller:

$criteria = new CDbCriteria;
$criteria->select = array('all_day','end','id','start');
$criteria->condition = 'user_id ='.$user->id;
$events = Calendar::model()->findAll($criteria);
foreach($events as $event) {
  $event->title = 'test title';
}
echo CJSON::encode($events);

In my Calendar model, I've added a new property called $title:

public $title;

But then when I go to echo the JSON, title doesn't show up...

[{"all_day":false,"end":"-948712553","id":"2","start":"-146154706"}]

What do I need to do to add title to the JSON result set?

like image 391
ews2001 Avatar asked Aug 07 '12 18:08

ews2001


2 Answers

This happens because CJSON::encode encodes the attributes of each model, and custom properties are not added to the attributes of the model. The way custom properties are added to the model, this can not be done in a straightforward way.

I did come up with a workaround though taking the hint from this answer:

$events = Calendar::model()->findAll($criteria);
$rows=array();// we need this array
foreach($events as $i=>$event) {
    $event->title = 'test title';
    $rows[$i]=$event->attributes;
    $rows[$i]['title']=$event->title;
}

echo CJSON::encode($rows); // echo $rows instead of $events

The code above should work.

like image 123
bool.dev Avatar answered Nov 10 '22 12:11

bool.dev


you can extend your model and provide your new attribute like this:

    public function getTitle() {
        return "test title";
    }

    public function getAttributes($names = true) {
        $attrs = parent::getAttributes($names);
        $attrs['title'] = $this->getTitle();

        return $attrs;
    }
like image 26
Mahdi Hijazi Avatar answered Nov 10 '22 14:11

Mahdi Hijazi