我试图在每个帖子上只加载最后3条评论

时间:2017-11-27 07:20:37

标签: php laravel-5 greatest-n-per-group

我希望在每篇帖子中获得最后三条评论的所有帖子。我的关系是

public function comments()
{
   return $this->hasMany('App\Commentpostfeed','post_id')->take(3);
}

每当我调用它时,这将只返回3条评论,而不是每篇帖子3条评论。 我用这种方式:

1:

Postfeed::with(['comment' => function($query) {
         $query->orderBy('created_at', 'desc')->take(3); }]);

2:

 $postings = Postfeed::with('comments')->get();

但得到相同的结果。请帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

使用普通的mysql(如果使用Mysql)查询,您可以使用以下查询获得每篇帖子最近的3条评论,该查询通过匹配created_at重新加入评论表

SELECT p.*,c.*
FROM posts p 
JOIN comments c ON p.`id` = c.`post_id`
LEFT JOIN comments c1 ON c.`post_id` = c1.`post_id` AND c.`created_at` <= c1.`created_at`
GROUP BY p.`id`,c.`id`
HAVING COUNT(*) <=3
ORDER BY p.`id`,c.`created_at` DESC

Sample Demo

使用laravel的查询构建器,您可以编写类似于

的内容
$posts = DB::table('posts as p')
    ->select('p.*,c.*')
    ->join('comments c', 'p.id', '=', 'c.post_id')
    ->leftJoin('comments as c1', function ($join) {
                $join->on('c.post_id', '=', 'c1.post_id')->where('c.created_at', '<=', 'c1.created_at');
            })
    ->groupBy('p.id')
    ->groupBy('c.id')
    ->having('COUNT(*)', '<=', 3)
    ->orderBy('p.id', 'asc')
    ->orderBy('c.created_at', 'desc')
    ->get();

答案 1 :(得分:0)

您可以在BaseModel中创建一个范围,如下所示:

<?php

class BaseModel extends \Eloquent {

    /**
     * query scope nPerGroup
     * 
     * @return void
     */
    public function scopeNPerGroup($query, $group, $n = 10)
    {
        // queried table
        $table = ($this->getTable());

        // initialize MySQL variables inline
        $query->from( DB::raw("(SELECT @rank:=0, @group:=0) as vars, {$table}") );

        // if no columns already selected, let's select *
        if ( ! $query->getQuery()->columns) 
        { 
            $query->select("{$table}.*"); 
        }

        // make sure column aliases are unique
        $groupAlias = 'group_'.md5(time());
        $rankAlias  = 'rank_'.md5(time());

        // apply mysql variables
        $query->addSelect(DB::raw(
            "@rank := IF(@group = {$group}, @rank+1, 1) as {$rankAlias}, @group := {$group} as {$groupAlias}"
        ));

        // make sure first order clause is the group order
        $query->getQuery()->orders = (array) $query->getQuery()->orders;
        array_unshift($query->getQuery()->orders, ['column' => $group, 'direction' => 'asc']);

        // prepare subquery
        $subQuery = $query->toSql();

        // prepare new main base Query\Builder
        $newBase = $this->newQuery()
            ->from(DB::raw("({$subQuery}) as {$table}"))
            ->mergeBindings($query->getQuery())
            ->where($rankAlias, '<=', $n)
            ->getQuery();

        // replace underlying builder to get rid of previous clauses
        $query->setQuery($newBase);
    }

}

在Postfeed模型中:

<?php

class Postfeed extends BaseModel {

    /**
     * Get latest 3 comments from hasMany relation.
     *
     * @return Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function latestComments()
    {
        return $this->comments()->latest()->nPerGroup('post_id', 3);
    }

    /**
     * Postfeed has many Commentpostfeeds
     *
     * @return Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function comments()
    {
        return $this->hasMany('App\Commentpostfeed','post_id');
    }

}

并获得最新评论的帖子:

$posts = Postfeed::with('latestComments')->get();

Ps: