2 个回答

你可以用 Eloquent ORM 来进行数据库查询。假设现在有两个模型,Comment 和 Reply,并且它们之间是有一对多关系。
Comment 模型:


// app/Models/Comment.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function replies()
    {
        return $this->hasMany(Reply::class);
    }
}

Reply 模型:

// app/Models/Reply.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Reply extends Model
{
    public function comment()
    {
        return $this->belongsTo(Comment::class);
    }
}

在 config/app.php 文件中注册模型:


'aliases' => [
    // ...
    'Comment' => App\Models\Comment::class,
    'Reply' => App\Models\Reply::class,
],

你得先写那两个模型,再用下面查询方法:

use App\Models\Comment;
use Illuminate\Support\Facades\DB;

$commentsWithTop5Replies = Comment::with(['replies' => function ($query) {
    $query->select('id', 'comment_id', 'content', 'created_at')
        ->selectSub(
            DB::raw('ROW_NUMBER() OVER (PARTITION BY comment_id ORDER BY created_at DESC)'),
            'reply_rank'
        )
        ->fromSub(function ($query) {
            $query->from('replies')->select('id', 'comment_id', 'content', 'created_at');
        }, 'replies_sub')
        ->where('reply_rank', '<=', 5);
}])->get();

这样就好了

select *
from (select *, row_number() over (partition by comment_id) as w
      from reply) as t
where w <= 5

支持窗口函数就用这个试试. mysql8支持.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题