Bug Magnet
Bug Magnet

Reputation: 2668

Yii ActiveRecord using with() not finding joined record

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?

Upvotes: 0

Views: 152

Answers (1)

acorncom
acorncom

Reputation: 5955

Generally, you can't have this:

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

and this:

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

both use the user_id key unless both your tables have a user_id key as their primary key. More likely, what you're after is this, like you have:

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

But what that equates to is the SQL statement:

user.id = userProfile.user_id 

If that isn't what you want, then you'll need to adjust accordingly. One of the most helpful things for figuring this out is either turning on basic logging of your SQL statements or using the Yii debug toolbar Makes it much easier to see what SQL is being run vs. what you thought would be run.

Upvotes: 1

Related Questions