Select only one column from belonging table using with() statement

Let’s say we have table User and Post. User can create multiple posts and one post is belonging only to a single user.

When I want to display all users, I want to display all belonging posts for every user, which is a perfect place for eager loading. You can use it like:




User::find()->where(['active'=>1])->with('posts')->all()



The code above will produce two SQL statements:


select * from user where active=1;

select * from posts where user_id in 1,2,3,4....

This will generate all users and all belonging posts, right.

But how can I say that I only want postTitle column from the posts table?


select * from user where active=1;

select postTitle from posts where user_id in 1,2,3,4....

Just specify query to use with relation:




User::find()->where(['active'=>1])->with(['posts' => function($q) {

      $q->select('postTitle');

}])->all()



Perfect, thank you.