Laravel有很多很多装载相关型号的计数

问题描述 投票:4回答:2

我试图链接4个表,并添加一个自定义字段计算通过使用laravel计算一些相关表的ID。我在SQL中有这个做我想要的,但我认为它可以提高效率:

DB::select('SELECT 
                        posts.*,
                          users.id AS users_id, users.email,users.username,
                          GROUP_CONCAT(tags.tag ORDER BY posts_tags.id) AS tags,
                          COUNT(DISTINCT comments.id) AS NumComments, 
                          COUNT(DISTINCT vote.id) AS NumVotes
                        FROM 
                          posts    
                          LEFT JOIN comments ON comments.posts_id = posts.id
                          LEFT JOIN users ON users.id = posts.author_id
                          LEFT JOIN vote  ON vote.posts_id = posts.id
                          LEFT JOIN posts_tags  ON posts_tags.posts_id = posts.id
                          LEFT JOIN tags  ON tags.id = posts_tags.tags_id

                        GROUP BY 
                          posts.id, 
                          posts.post_title');

我尝试使用eloquent实现它:

$trending=Posts::with(array('comments' => function($query)
                {
                    $query->select(DB::raw('COUNT(DISTINCT comments.id) AS NumComments'));

                },'user','vote','tags'))->get();

但是,NumComments值未显示在查询结果中。有什么线索怎么回事呢?

php laravel-4 many-to-many eloquent pivot-table
2个回答
11
投票

你不能使用with这样做,因为它执行单独的查询。

你需要的是简单的join。只需将您拥有的查询翻译为:

Posts::join('comments as c', 'posts.id', '=', 'c.id')
    ->selectRaw('posts.*, count(distinct c.id) as numComments')
    ->groupBy('posts.id', 'posts.post_title')
    ->with('user', 'vote', 'tags')
    ->get();

然后集合中的每个帖子都有count属性:

$post->numComments;

但是,您可以通过以下关系轻松实现:

虽然第一种解决方案在性能方面更好(除非你有大数据,否则可能不会引人注意)

// helper relation
public function commentsCount()
{
    return $this->hasOne('Comment')->selectRaw('posts_id, count(*) as aggregate')->groupBy('posts_id');
}

// accessor for convenience
public function getCommentsCountAttribute()
{
    // if relation not loaded already, let's load it now
    if ( ! array_key_exists('commentsCount', $this->relations)) $this->load('commentsCount');

    return $this->getRelation('commentsCount')->aggregate;
}

这将允许您这样做:

$posts = Posts::with('commentsCount', 'tags', ....)->get();
// then each post:
$post->commentsCount;

对于很多很多的关系:

public function tagsCount()
{
    return $this->belongsToMany('Tag')->selectRaw('count(tags.id) as aggregate')->groupBy('pivot_posts_id');
}

public function getTagsCountAttribute()
{
    if ( ! array_key_exists('tagsCount', $this->relations)) $this->load('tagsCount');

    $related = $this->getRelation('tagsCount')->first();

    return ($related) ? $related->aggregate : 0;
}

更多这样的例子可以在这里找到http://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/


0
投票

从laravel 5.3开始,你就可以做到这一点

withCount('comments','tags');

并称之为这样

$post->comments_count;

laravel 5.3 added withCount

© www.soinside.com 2019 - 2024. All rights reserved.