M
M
Max Khartanovych2016-03-26 18:00:47
Yii
Max Khartanovych, 2016-03-26 18:00:47

Yii2 AR: Joining with Relations?

I don't quite understand the behavior of Active Record in Yii2 when we use the
joinWith();
Code example method

// Relation is has many
return $this->hasMany(Cars::className(), ['user_id' => 'id']);

// Create and execute query to the db
User::find()->select(['user.*', 'cars.*'])->joinWith(['cars'])->where(['user.id' => $id])->one()

This code generates 2 requests
SELECT `user`.*, `cars`.* FROM `user` LEFT JOIN `cars` ON `user`.`id` = `cars`.`user_id` WHERE `user`.`id`='54'

SELECT * FROM `cars` WHERE `user_id`=54

In the case of has one, the behavior is the same.
Yii2 version: 2.0.7
PHP version: PHP 5.6.15-1~dotdeb+7.1 (cli)
Operating system: Linux api 3.2.0-4-amd64 #1 SMP Debian 3.2.57-3 x86_64

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
enchikiben, 2016-03-26
@EnChikiben

Yii2 abandoned join in favor of two separate queries

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question