In laravel, the with() method is used as "hungry loading", which means that laravel will preload the exact relationship with the main model. Using this method can alleviate the "1 N" problem Query problems, only "1 1" queries can solve the problem.
#The operating environment of this article: Windows 10 system, Laravel version 6, Dell G3 computer.
How to use the with method in laravel
with()
with() method is Used as "hungry loading", this mainly means that laravel will preload the exact relationship with the main model. This is very helpful if you want to add all the relationships in a model. Because "hungry loading" alleviates the 1N query problem, it only takes 11 queries to solve the problem, which significantly improves the query speed.
For example:
user > hasMany > post $users = User::with('posts')->get(); foreach($users as $user){ $users->posts; // posts已经被加载了,没有增加DB查询 }
Extension:
has()
has() method is based on the association relationship Filters the query results of the model, so its function is very similar to the where condition. If you only use has('post'), it means that you only want to get this model, which has at least one post association.
For example:
user > hasMany > post //User至少有一条post的关联关系 $users = User::has('post')->get();
You can also use "." to construct nested has statements.
For example:
user > hasMany > post $user = User::has('post.votes', '>', '3')->get();
Related recommendations: The latest five Laravel video tutorials
The above is the detailed content of How to use the with method in laravel. For more information, please follow other related articles on the PHP Chinese website!