Yii CDbCriteria和Model-> findAll,如何添加自定义列?

ews*_*001 8 php yii

我在Yii有一个日历应用程序,我按用户存储事件.我想动态地为每个事件建立一个标题.

这段代码在我的控制器中:

$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);
Run Code Online (Sandbox Code Playgroud)

在我的日历模型中,我添加了一个名为$ title的新属性:

public $title;
Run Code Online (Sandbox Code Playgroud)

但是当我去回应JSON时,标题没有出现......

[{"all_day":false,"end":"-948712553","id":"2","start":"-146154706"}]
Run Code Online (Sandbox Code Playgroud)

要将标题添加到JSON结果集,我需要做什么?

boo*_*dev 5

发生这种情况是因为对每个模型CJSON::encode属性进行编码,并且不会将自定义属性添加到模型的属性中.自定义属性添加到模型的方式,这不能以简单的方式完成.

虽然从这个答案中得到了暗示,但我确实想出了一个解决方法:

$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
Run Code Online (Sandbox Code Playgroud)

上面的代码应该有效.