假设您有Post->hasMany->Like
关系并且您已将喜欢关系声明为:
class Post{
public function likes(){
return $this->hasMany('Like');
}
}
创建一个新函数说likeCountRelation
:
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;
default:
return parent::__get($attribute);
}
}
或者您可以将 getattribute 函数用作:
public function getLikesCountAttribute(){
return $this->likesCountRelation->first() ? $this->likesCountRelation->first()->count : 0;
}
并简单地访问 likesCount,因为$post->likesCount
您甚至可以像这样急切地加载它:
$posts=Post::with('likesCountRelation')->get();
foreach($post as $post){
$post->likesCount;
}
NOTE:
相同的逻辑可用于变形许多关系。