【问题标题】:Returning counts of a relationship model in Laravel在 Laravel 中返​​回关系模型的计数
【发布时间】:2014-11-06 08:57:47
【问题描述】:

我有一个用户和注释模型以及一个用于存储用户喜欢的注释的数据透视表 user_like。注释表还通过 hasMany 关系与另一个模型(范围)关联。我正在尝试返回所有注释及其用户、范围和喜欢的总数。

下面的代码适用于用户、范围甚至喜欢。但是,我只对返回喜欢的计数感兴趣,而不是实际值(即喜欢注释的用户列表)。有没有办法只包括关系中一个模型的计数?

雄辩的查询:

    $annotations = Annotation::with('ranges')
                              ->with('likes')
                              ->with('author')
                              ->where('document_id', $docid)->get()->toArray();

型号:

class Annotation extends Eloquent {

    public function ranges()
    {
        return $this->hasMany('Range');
    }

    public function author()
    {
        return $this->belongsTo('User', 'user_id');
    }

    public function likes()
    {
        return $this->belongsToMany('User', 'annotation_like');
    }

    public function countOfLikes()
    {
        return $this->likes()->count();
    }

}

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    如果您想使用即时加载检索多个注释的计数,那么您需要以下“帮助”关系设置:

    public function countLikesRelation()
    {
        return $this->belongsTo('User','annonation_like')->selectRaw('annotation_like, count(*) as count')->groupBy('annotation_like');
    }
    
    // then you can access it as such:
    
    $annotations= Annotation::with('countLikesRelation')->get();
    $annotations->first()->countLikesRelation->count;
    
    // to make it easier, we create an accessor to the count attribute
    
    public function getLikesCountAttribute()
    {
        return $this->countLikesRelation->count;
    }
    
    //And then, simply use
    
    $annotations->first()->sectionsCount;
    

    【讨论】:

    • 你搞错了,是belongsToMany不是belongTo,所以需要稍微调整一下,不过思路不错
    • @mysteryos 这很好用。谢谢。但是,它确实也带来了用户表中的所有内容。生成的查询是这样的:“select annotation_id, count() as count, users.,.....”。我想知道为什么选择中有 users.* 。有什么想法吗?
    猜你喜欢
    • 2014-10-15
    • 2020-11-06
    • 2017-11-23
    • 2015-04-18
    • 2019-05-16
    • 2013-07-04
    • 1970-01-01
    • 2020-11-15
    • 2016-02-29
    相关资源
    最近更新 更多