【问题标题】:Add attribute to activerecord after findAll call in YII framework在 YII 框架中调用 findAll 后向 activerecord 添加属性
【发布时间】:2012-12-17 15:16:08
【问题描述】:

我正在调用findAll 方法,我得到4 个字段。我现在想再添加一个名为$owned 的字段。 所以这意味着在我从表中获取记录后,结果数据记录应该包含拥有的字段。 此外,$owned 字段是动态的,取决于用户是否是组的所有者。我尝试使用afterFind。但它也不起作用。令人惊讶的是,它将属性$owned 添加到对象而不是属性。 我在控制器中使用CJSON::encode($model) 来查看输出。$owned 字段未显示。 下面是代码

/**
*
* The followings are the available columns in table 'group':
* @property integer $id
* @property string $name
* @property string $created_at
* @property string $updated_at
*/

class Group extends CActiveRecord
{
//adding owned property for groups.true if user is owner

    public $owned;

protected function afterFind()
{

    parent::afterFind();
    //if user is owner of group its true
    $this->owned = true;

}

【问题讨论】:

  • 您可以在您的问题中发布您的整个Group 模型吗?您是否通过在 rules() 方法中声明 owned 将其定义为属性?
  • 你可以尝试在分配后打电话给parent::afterFind()(不确定它会改变什么,但你可以试一试)

标签: activerecord yii


【解决方案1】:

试试下面的代码:

public function init()
    {
        $this->onAfterFind=array($this,'afterFindCustom');
        parent::init();
    }

    public function afterFindCustom()
    {
        $this->owned = true;
        parent::afterFind();
    }

【讨论】:

  • 谢谢萨维什。我收到错误“(!)致命错误:在第 91 行的 C:\wamp\yii-1.1.12.b600af\framework\collections\CListIterator.php 中达到了 '100' 的最大函数嵌套级别,正在中止!”。 afterFindCustom 中的 parent::afterFind() 行会导致此错误。
  • 是的,您必须从 afterFindCustom() 中删除 parent::afterFind() 调用。 onAfterFind 事件由 afterFind 函数触发,因此再次调用它意味着您正在创建一个无限循环。无需返回任何东西或在那里调用父函数。
  • 感谢暴雪...仍然无法正常工作..在我的代码中 $groups = Tabs::model()->findAll('user_id = :userID',array(':userID'=> $用户ID));。现在获取后有什么方法可以将任何其他属性添加到 $groups 对象数组。因为我无法添加任何东西。在执行 print_r 时,它会向我转储一个具有许多属性和所有属性的整个对象......
【解决方案2】:

我终于知道了。这是 CJSON::encode 问题的问题。此方法仅对模型的属性进行编码。它不编码任何关系或动态属性。所以我编写了自己的函数并且它有效。!

希望这对将来的某人有所帮助

谢谢大家 史密斯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多