yii activerecord使用()找不到加入记录



我有两个模型:用户和用户fofile

在用户模型中,我定义了以下关系:

  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(
                'userProfile' => array(self::HAS_ONE, 'UserProfile', 'user_id'),
            );
  }

在UserProfile中,我定义了此关系:

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(
        'user' => array(self::BELONGS_TO, 'User', 'user_id'),
    );
}

现在,当我在控制器中运行以下代码时:

$user = User::model()->with('userProfile')->findByPK($userId);
    $userProfile = $user->userProfile;
    print_r($userProfile);

$ userProfile变量为null。我已经检查并仔细检查了数据库和代码,我也重新阅读了YII文档,似乎一切都是应有的。但这只是拒绝工作!

知道我在做什么错?

通常,您不能拥有:

'userProfile' => array(self::HAS_ONE, 'UserProfile', 'user_id'),

和此:

'user' => array(self::BELONGS_TO, 'User', 'user_id'),

除非您的两个表都将User_id键作为其主要密钥,否则两者都使用user_id键。更有可能的是,您所追求的是:

'userProfile' => array(self::HAS_ONE, 'UserProfile', 'user_id'),

但是等于sql语句:

user.id = userProfile.user_id 

如果不是您想要的,那么您需要进行相应的调整。解决此问题的最有用的事情之一是打开SQL语句的基本日志记录,或者使用YII调试工具栏使您更容易查看正在运行的SQL而不是您认为会运行的是什么。

最新更新