Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?
Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?
With
with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. With đi kèm với khái niệm eager loading, tức là đi kèm với main model, Laravel sẽ load thêm dữ liệu của model có quan hệ với model chính. Ví dụ
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
$users->post; // posts is already loaded and no additional DB query is run
}
Has
If you just use has('relation') that means you only want to get the models that have at least one related model in this relation. --> là 1 dạng filter (sử dụng where), khi muốn lấy các model chính có ít nhất 1 model con
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
WhereHas
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check. --> giống như has nhưng thêm điều kiện filter
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
Comments
Post a Comment