I have a complex Model with multiple defined relations. In this example I would want to count the Like
model and create a property named likes
so it can be returned from a REST service.
Is it possible to eager load a model count into a dynamic property?
$beat = Post::with(
array(
'user',
'likes' => function($q){
$q->count();
}
))
->where('id', $id)
->first();
You should use the SQL
Group By
statement in order to make it works. You can rewrite your query like the following one.The result of
likes
is a Collection object with one element. I'm assuming the relationship between modelPost
andLike
isPost
hasMany
Like
. So you can access the count like this.I'm not tested code above but it should works.
Assuming you are having
Post->hasMany->Like
relationship and you have declared likes relationship as:create a new function say
likeCountRelation
as:now you can override
__get()
function as:or you can use getattribute function as :
and simply access likesCount as
$post->likesCount
you can even eager load it like:NOTE:
Same logic can be used for morph many relationships.