本文介绍了我正在尝试仅在每个帖子上加载最后3条评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望获得所有帖子,每个帖子都带有最后三个评论.我的关系是

i want get all posts with last three comment on each post. my relation is

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

每当我调用它时,它总共只会返回3条评论,而不是每个帖子3条评论.我用这种方式:

This would return only 3 comments total whenever I called it instead of 3 comments per post. i use this way :

1:

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

2:

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

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

but getting same result. please help me out for this problem.

推荐答案

您可以像这样在BaseModel中创建作用域:

You can create a scope in the BaseModel like this :

<?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模型中:

And in the Postfeed Model :

<?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');
    }

}

并获得带有最新评论的帖子:

And to get the posts with the latest comments :

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

Ps:

  • Source
  • For many to many relationships

这篇关于我正在尝试仅在每个帖子上加载最后3条评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 01:31