M
M
Mors Clamor2019-10-05 19:53:01
Yii
Mors Clamor, 2019-10-05 19:53:01

Yii2 get data from two tables at once?

Hello. I need to get data from 2 tables - users and users_info. I read that in the model (user turns out) you need to create a getter like getUsersinfo where you need to write something like Question: why can't you work with 2 models in the controller and what is the difference between setting hasOne connections and the above method. And which is better to use?
return static::findOne(['user_id'=>$id]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2019-10-05
@66demon666

If you have a relationship, then using this will get records from two tables.

// relation
public function getUserInfo()
{
     return $this->hasOne(User::class, ['id' => 'user_id']);
}
//query
$model = User::find()->with('userInfo')->one();

You can remove data from a connection like this . Here is a lot of useful information for working with connected data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question