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