Problem
has, with and whereHas can sometimes be confusing for beginner developers. Let’s give some perspective on what each of those mean
Solution
with() is generally used with eager loading, which is a quick way to pull related models. Basically, it means that, along with the main model, Laravel will preload the listed relationship(s). This is beneficial when you need to load additional data and want to avoid making N+1 DB bad practices. With eager loading, you run only one additional DB query instead of potentially hundreds of additional queries.
Example:
User > hasMany > Organization
$users = User::with(‘organizations’)->get();
foreach($users as $user){
$users->organizations; // posts is already loaded and no additional DB query is run
}
Has
has() is used to filter the selecting model based on the selected relationship. It is basically a where method for relations. If you just use has(‘organization’), using the same example of users and organizations, it would mean that it will pull all the users that have at least one organization in their ‘portfolio’.
Example:
User > hasMany > Organization
$users = User::has(‘organizations’)->get();
// only users that have at least one organization in their portfolio are contained in the collection
WhereHas
whereHas() is almost the same as has(). It just allows you to specify additional filters for the related model to be checked.
Example:
User > hasMany > Organization
$users = User::whereHas(‘organizations’, function($q){
$q->where(‘created_at’, ‘>=’, ‘2020-01-01 00:00:00’);
})->get();
// only users that have organizations created at the beginning of 2020 onward are returned
from Linux Hint https://ift.tt/2XX6F2F
0 Comments