P
P
Peppa Pig2015-09-04 22:30:32
Yii
Peppa Pig, 2015-09-04 22:30:32

Yii2 how to make a one to one relationship?

Hello.
Prompt how correctly to implement communication one to one.
There is a table of profiles, there is a table of users.
In the profile controller, I'm trying to get a complete user object with fields from User and Profile.

$profile = Profile::find()->select('*')->joinWith('user',true,'RIGHT JOIN')->where(['username'=>$login])->one();

If you look in the debugger, then the request is more or less correct. But in the $profile object there are only user fields. And it seems to me that this approach is not entirely correct .. Please tell me how to do this correctly

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
HaruAtari, 2015-09-04
@kitty04

In the user table, write the relationship:

public function getProfile() {
  return $this->hasOne(Profile::class,['id'=>'id']);
}

And the profile becomes available through the property.
$user = User::find()->andWhere(['username'=>$login])->one();
$user->name; // своятво пользователя
$user->profile->id // свойство профиля

If you want with one request, then when selecting, specify the model that you want to pull
$user = User::find()->with('profile')->andWhere(['username'=>$login])->one();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question