繁体   English   中英

Yii-Belongs_To正在工作,现在引发错误

[英]Yii - Belongs_To was working, now throws error

我有一个用户和帐户模型。 关系是用户属于帐户,帐户有许多用户。

这是两者的模型代码:

用户模型

public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'account' => array(self::BELONGS_TO, 'Account', 'account_id'),
    );
}

帐户模型

public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'users' => array(self::HAS_MANY, 'User', 'account_id'),
                    'userCount'=>array(self::STAT,'User','account_id'),
            );
}

我在UserIdentity.php中有以下代码可用于登录WAS正常运行的代码:

public function authenticate()
{
    $user=User::model()->findByAttributes(array('username'=>$this->username));
    if($user===null)
        $this->errorCode=self::ERROR_USERNAME_INVALID;
    else{
                if($user->password!==$user->encrypt($this->password))
                    $this->errorCode=self::ERROR_PASSWORD_INVALID;
                else{
                    $this->_id=$user->id;
                    if($user->last_login_time==null)
                        $lastLogin=time();
                    else
                        $lastLogin=strtotime($user->last_login_time);
                    $this->setState('lastLoginTime', $lastLogin);
                    $this->setState('account',array('id'=>$user->account->id,'name'=>$user->account->name,));
                    $this->errorCode=self::ERROR_NONE;
                }
            }
    return !$this->errorCode;
}

当我向该帐户添加另一个用户时,它开始出现错误:

PHP注意:尝试获取非对象的属性

错误指向

$this->setState('account',array('id'=>$user->account->id,'name'=>$user->account->name,));

当分成多行时:

错误所在是'id'=>$user->account->id,

为了解决这个问题,我只是将其更改为:

$account=Account::model()->findByPk($user->account_id);
$this->setState('account',array('id'=>$account->id,'name'=>$account->name,));

因此,当我只有一个用户时,该关系可以正常工作,但是当我有两个用户时,该关系将失败。 我可以像上面一样继续使用Yii,但是我确实喜欢直接访问对象的简单性。 我没有正确建立关系吗? 为什么现在在一个帐户中只有2个用户无法使用此功能?

编辑:

var_dump($user) : //pastebin.com/TEyrFnme

同样有趣的是,我可以使用以下帐户从该帐户访问该用户: $users=$account->users; 并访问所有$user[0]属性就可以了。 因此,相反地,这种关系似乎正在发挥作用,只是继续前进似乎有困难。

不要在模型中声明与关系同名的变量。

public $account;

会阻止模型寻找account关系,因为Yii会先检查(并使用)实际属性,然后再检查同名关系。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM