問題描述
我有一個具有多個定義關系的復雜模型.在這個例子中,我想計算 Like
模型并創建一個名為 likes
的屬性,以便它可以從 REST 服務返回.
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();
推薦答案
假設您有 Post->hasMany->Like
關系,并且您已聲明 Likes 關系為:
Assuming you are having Post->hasMany->Like
relationship and you have declared likes relationship as:
class Post{
public function likes(){
return $this->hasMany('Like');
}
}
創建一個新函數,比如 likeCountRelation
為:
create a new function say likeCountRelation
as:
public function likeCountRelation()
{
$a = $this->likes();
return $a->selectRaw($a->getForeignKey() . ', count(*) as count')->groupBy($a->getForeignKey());
}
現在您可以將 __get()
函數重寫為:
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);
}
}
或者你可以使用 getattribute 函數:
or you can use getattribute function as :
public function getLikesCountAttribute(){
return $this->likesCountRelation->first() ? $this->likesCountRelation->first()->count : 0;
}
并且只需將 likesCount 作為 $post->likesCount
訪問,您甚至可以像這樣急切加載它:
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 雄辯的急切加載關系計數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!