Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between $with and $joinWith in Yii2 and when to use them?

Tags:

php

yii

yii2

In the API documentation it is specified that

  • $joinWith - A list of relations that this query should be joined with
  • $with - A list of relations that this query should be performed with

What is the difference between these ActiveQuery property and under what situation should we use $joinWith and $with?

like image 319
NAT3863 Avatar asked Sep 01 '14 06:09

NAT3863


People also ask

How to join two tables in Yii2?

Setting those relations in the models tells explicitly to Yii2 how to join those tables. Yii2 by default assumes that foreign keys are named in a specific way, and in your case when joining, Yii2 assumes that your post table has a category_id attribute as a foreign key to category table.

What is joinWith?

joinWith uses JOIN to include the relations in the original query while with does not.

What is active query in Yii?

An ActiveQuery can be a normal query or be used in a relational context. ActiveQuery instances are usually created by yii\db\ActiveRecord::find() and yii\db\ActiveRecord::findBySql(). Relational queries are created by yii\db\ActiveRecord::hasOne() and yii\db\ActiveRecord::hasMany().


1 Answers

joinWith uses JOIN to include the relations in the original query while with does not.

To illustrate further, consider a class Post with a relation comments as follows:

class Post extends \yii\db\ActiveRecord {     ...     public function getComments() {         return $this->hasMany(Comment::className(), ['post_id' => 'id']);     } } 

Using with the code below:

$post = Post::find()->with('comments'); 

results in the following sql queries:

SELECT `post`.* FROM `post`; SELECT `comment`.* FROM `comment` WHERE post_id IN (...) 

Whereas the joinWith code below:

$post = Post::find()->joinWith('comments', true) 

results in the queries:

SELECT `post`.* FROM post LEFT JOIN `comment` comments ON post.`id` = comments.`post_id`; SELECT `comment`.* FROM `comment` WHERE post_id IN (...); 

As a result, when using joinWith you may order by/filter/group by the relation. You may have to disambiguate the column names yourself.

Reference: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#lazy-eager-loading

like image 62
topher Avatar answered Sep 22 '22 01:09

topher