8

我在 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);

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

public $title;

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

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

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

4

2 回答 2

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

上面的代码应该可以工作。

于 2012-08-07T21:58:25.360 回答
4

您可以扩展您的模型并提供您的新属性,如下所示:

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

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

        return $attrs;
    }
于 2013-07-11T23:40:35.690 回答