In LaravelEloquent, the with () function returns only the specified column.

Source: Internet
Author: User
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'));}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.