In LaravelEloquent, the with () function only returns the specified column. Laravel provides the Eager Loading to use the with () method to alleviate the N + 1 problem. However, there are still some problems in actual use, with () will directly query all the fields in the table, and we may only need some specified fields.
Assume that we have two tables: user and posts. each User can have multiple Posts, and each Post can only belong to one User. The relationships defined in User Model and Post Model are as follows:
// User.php public function post(){ return $this->hasMany('post');}// Post.phppublic function user(){ return $this->belongsTo('user');}
Through the with () method, we can obtain all Posts and find the corresponding User information at the same time. you can use this method:
public function getAllPosts() { return Post::with('user')->get();}
This will actually execute the following two SQL statements:
select * from `posts`select * from `users` where `users`.`id` in (<1>, <2>)
However, we do not need all the fields in the User table. for example, we only need the id and username fields:
select * from `posts`select id,username from `users` where `users`.`id` in (<1>, <2>)
We can achieve this through the following two methods.
Method 1: specify
Post::with(array('user'=>function($query){ $query->select('id','username');}))->get();Method 2: modify the Model file
Modify the user () method in the Post. php file:
public function user(){ return $this->belongsTo('User')->select(array('id', 'username'));}