Laravel with craving for loading specified fields

Source: Internet
Author: User

In an associative query using Laravel, we often use with methods to avoid N+1 queries, but with all the fields associated with the target are queried, which is of course not allowed for us with obsessive-compulsive disorder.

At this point we can use the following technique to query only the part of the target associated field when using with:

$topics=Topic::Limit(2)->With([' User '=>function ( $query { $query ->select  ( ' id ' , ' username ' ) ;}]) -< Span class= "token operator" >>get ("          

But every time the query is written so tedious, really good? Instead, use the Laravel scope query to encapsulate it:

Defining a range query in the Model base class

ClassBasemodelExtends\eloquent{PublicfunctionScopewithcertain($query,$relation,Array$columns){Return$query->With([$relation=>function($query)Use( $columns { $query -> select (array_merge< Span class= "token punctuation" > ([ ' id ' ] $columns }]) }}        /span>                

The

inherits the base class in our normal Model class:

class  Topic extends basemodel {public function user () {return  $this -< Span class= "token operator" >>belongsto ( ' User ' }}           

And then it's convenient to use:

 $topics = topic::limit  (2) ->withcertain ( ' user ' [ ' username ' ]-> get ()               

Laravel with craving to load specified fields

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.