Home > PHP Framework > Laravel > body text

How to use the with method in laravel

WBOY
Release: 2022-01-13 16:48:57
Original
8278 people have browsed it

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.

How to use the with method in laravel

#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查询
}
Copy after login

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();
Copy after login

You can also use "." to construct nested has statements.

For example:

user > hasMany > post
$user = User::has('post.votes', '>', '3')->get();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!