orm - Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean? -


i've found concept , meaning behind these methods little confusing, possible explain me difference between has , with is, in context of example (if possible)?

with

with() eager loading. means, along main model, laravel preload relationship(s) specify. helpful if have collection of models , want load relation of them. because eager loading run 1 additional db query instead of 1 every model in collection.

example:

user > hasmany > post

$users = user::with('posts')->get(); foreach($users $user){     $users->posts; // posts loaded , no additional db query run } 

has

has() filter selecting model based on relationship. acts normal condition. if use has('relation') means want models have @ least 1 related model in relation.

example:

user > hasmany > post

$users = user::has('posts')->get(); // users have @ least 1 post contained in collection 

wherehas

wherehas() works same has() allows specify additional filters related model check.

example:

user > hasmany > post

$users = user::wherehas('posts', function($q){     $q->where('created_at', '>=', '2015-01-01 00:00:00'); })->get(); // users have posts year returned 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -