laravel 4 雄辩的急切负载关系计数

laravel 4 eloquent eager load relation count(laravel 4 雄辩的急切负载关系计数)
本文介绍了laravel 4 雄辩的急切负载关系计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有多个已定义关系的复杂模型.在此示例中,我想计算 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;
}

只需以 $post->likesCount 的形式访问 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 雄辩的急切负载关系计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)