0

I have two models: User and UserProfile

Inside the User model, I have defined the following relations:

  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'),
            );
  }

In UserProfile, I have this relation defined:

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'),
    );
}

Now when I run the following code in my controller:

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

    $userProfile = $user->userProfile;

    print_r($userProfile);

The $userProfile variable is null. I've checked and double-checked the database and code, I've re-read the Yii documentation as well, and seems everything is the way it should be. But it just refuses to work!

Any idea what am I doing wrong?

4

1 回答 1

1

一般来说,你不能这样:

'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 与您认为将运行的 SQL 变得更加容易。

于 2012-11-08T16:37:10.680 回答