where(filter condition);})->get()"."/> where(filter condition);})->get()".">

Home >PHP Framework >Laravel >What is wherehas used for in laravel?

What is wherehas used for in laravel?

WBOY
WBOYOriginal
2022-06-07 16:06:064849browse

In laravel, wherehas filters the query results of the model based on the association relationship, and allows you to add filter conditions for this model. It is often used to filter data about the slave table in the main table. The syntax is "User::whereHas ('from table', function($...){$...->where(filter condition);})->get()".

What is wherehas used for in laravel?

#The operating environment of this article: Windows 10 system, Laravel version 6, Dell G3 computer.

wherehas

with()

with() method in laravel is used for "eager loading", which mainly means that laravel The exact relationships will be preloaded 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查询
}

has()

has() method is based on association The relationship is used to filter 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();

whereHas()

whereHas() method The principle is basically the same as the has() method, but it allows you to add filter conditions to this model yourself.

For example:

user > hasMany > post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2017-11-29');
})->get();

[Related recommendations: laravel video tutorial]

The above is the detailed content of What is wherehas used for in laravel?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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