0

UserとUserProfileの2つのモデルがあります

Userモデル内で、次の関係を定義しました。

  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のドキュメントも読み直しましたが、すべてが本来あるべき姿であるようです。しかし、それはただ働くことを拒否します!

私が間違っていることは何ですか?

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 

それがあなたが望むものでない場合は、それに応じて調整する必要があります。これを理解するのに最も役立つことの1つは、SQLステートメントの基本的なログをオンにするか、Yiiデバッグツールバーを使用 することです。これにより、実行されているSQLと実行されると思われるSQLを簡単に確認できます。

于 2012-11-08T16:37:10.680 に答える