M
M
McMike2016-12-07 09:51:03
Yii
McMike, 2016-12-07 09:51:03

What is the difference between with and joinWith?

What is the difference between with and joinWith?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2016-12-07
@McMike

with - performs eager loading of related data
joinWith - performs eager loading/lazy loading of related data while using a JOIN built from relationships to fetch the main data.
For example, there is a model:

class User extends \yii\db\ActiveRecord {

    public function getPosts(){
       return $this->hasMany(Post::className(), ['user_id' => 'id']);
    }
}

User::find()->with('posts') will do the following:
1. Find all users using SELECT * FROM user
2. Select IDs from all found users
3. Find all related data using SELECT * FROM post WHERE user_id IN (1,2,3) // where 1,2,3 are identifiers found in the previous paragraph
4. Matches User and Post
User::find()->joinWith('posts') will do the same, but instead of the SELECT * FROM user query, the query
SELECT user.* FROM user
LEFT JOIN post ON post.user_id = user.id will be executed.
This is convenient for sorting data, for example. In addition, if joinWith parameter eagerLoading is set to false, steps 2-4 will not be executed, but the join will be simply formed and executed.

A
Alexey, 2016-12-07
@masterfreelance

look here

A
Anton, 2016-12-08
@karminski

An important difference between joinWith() and with() is that the first method "sticks together" the rows of two tables and allows you to work with the data of both the primary (primary) model and the related one. The second method will allow, after sampling, to work with data only from the main model.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question