laravel 4雄辩渴望的负载关系计数 [英] laravel 4 eloquent eager load relation count
问题描述
Like
model,并创建一个名为喜欢
的属性,以便它可以从REST服务。 可以将模型计数加载到动态属性中吗?
$ beat = Post :: with(
array(
'user',
'likes'=> function($ q){
$ q-> count();
}
))
- >其中('id',$ id)
- > first();
假设你有 - > hasMany->喜欢
关系,您已声明喜欢的关系为:
类帖子{
public function likes(){
return $ this-> hasMany('Like');
}
}
创建一个新功能,说 likeCountRelation
as:
public function likeCountRelation()
{
$ a = $ this-> likes();
return $ a-> selectRaw($ a-> getForeignKey()。',count(*)as count') - > groupBy($ a-> getForeignKey());
}
现在您可以覆盖 __ get()
函数为:
public function __get($ attribute)
{
if(array_key_exists($ attribute,$ this-> attributes)){
return $ this-> attributes [$ attribute];
}
switch($ attribute){
case'likesCount':
return $ this-> attributes [$ attribute] = $ this - > likesCountRelation-> first()? $ this-> likesCountRelation-> first() - > count:0;
break;
默认值:
return parent :: __ get($ attribute);
}
}
或者您可以使用getattribute函数:
public function getLikesCountAttribute(){
return $ this-> likesCountRelation-> first()? $ this-> likesCountRelation-> first() - > count:0;
}
只需访问像C code $ $ post->你可以加载它喜欢:
$ posts = Post :: with('likesCountRelation ) - >得到();
foreach($ post as $ post){
$ post-> likesCount;
}
注意:
逻辑可以用于变形许多关系。
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();
Assuming you are having Post->hasMany->Like
relationship and you have declared likes relationship as:
class Post{
public function likes(){
return $this->hasMany('Like');
}
}
create a new function say likeCountRelation
as:
public function likeCountRelation()
{
$a = $this->likes();
return $a->selectRaw($a->getForeignKey() . ', count(*) as count')->groupBy($a->getForeignKey());
}
now you can override __get()
function as:
public function __get($attribute)
{
if (array_key_exists($attribute, $this->attributes)) {
return $this->attributes[$attribute];
}
switch ($attribute) {
case 'likesCount':
return $this->attributes[$attribute] = $this->likesCountRelation->first() ? $this->likesCountRelation->first()->count : 0;
break;
default:
return parent::__get($attribute);
}
}
or you can use getattribute function as :
public function getLikesCountAttribute(){
return $this->likesCountRelation->first() ? $this->likesCountRelation->first()->count : 0;
}
and simply access likesCount as $post->likesCount
you can even eager load it like:
$posts=Post::with('likesCountRelation')->get();
foreach($post as $post){
$post->likesCount;
}
NOTE:
Same logic can be used for morph many relationships.
这篇关于laravel 4雄辩渴望的负载关系计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!