[英]Yii CDbCriteria and Model->findAll, how to add custom column?
I have a calendar app in Yii where I store events per user. 我在Yii有一个日历应用程序,我按用户存储事件。 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: 在我的日历模型中,我添加了一个名为$ title的新属性:
public $title;
But then when I go to echo the JSON, title doesn't show up... 但是当我去回应JSON时,标题没有出现......
[{"all_day":false,"end":"-948712553","id":"2","start":"-146154706"}]
What do I need to do to add title to the JSON result set? 要将标题添加到JSON结果集,我需要做什么?
This happens because CJSON::encode
encodes the attributes of each model, and custom properties are not added to the attributes of the model. 发生这种情况是因为
CJSON::encode
对每个模型的属性 CJSON::encode
编码,并且自定义属性不会添加到模型的属性中。 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. 上面的代码应该有效。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.