You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel Eloquent中按父级排序评论回复

评论按父ID排序展示的Laravel Eloquent实现问题

我需要实现评论回复按父ID排序展示,以下是相关数据库表结构、示例数据:

数据库表结构

CREATE TABLE `comments` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `slug` char(36) COLLATE utf8mb4_unicode_ci NOT NULL,
  `content` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `user_id` bigint NOT NULL,
  `comment_id` bigint NOT NULL DEFAULT '0', -- 父评论ID
  `depth_comment_id` bigint NOT NULL DEFAULT '0', -- 根评论ID
  `commentable_id` bigint NOT NULL,
  `commentable_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `comments_slug_unique` (`slug`)
)

示例数据

INSERT INTO `comments` (`id`, `slug`, `content`, `user_id`, `comment_id`, `depth_comment_id`, `commentable_id`, `commentable_type`, `created_at`, `updated_at`)
VALUES
    (1,'e074eb3a-b695-4c37-a063-37971084c6bd','test comment',1,0,0,1,'App\\Models\\Feed','2025-03-08 12:34:40','2025-03-08 12:34:40'),
    (2,'47891ac5-233f-4949-8e32-fda78543f61d','comment 2',1,0,0,1,'App\\Models\\Feed','2025-03-08 12:34:43','2025-03-08 12:34:43'),
    (3,'fe5f60c1-230e-407f-8b7b-f82fef40679a','abc',1,2,2,1,'App\\Models\\Feed','2025-03-08 12:35:08','2025-03-08 12:35:08'),
    (4,'0256e968-dfa9-444c-8a27-794d805e443e','abctest',1,2,2,1,'App\\Models\\Feed','2025-03-08 12:35:23','2025-03-08 12:35:23'),
    (5,'1608bc34-88ec-469c-8a1e-f32869525781','abctest child',1,3,2,1,'App\\Models\\Feed','2025-03-08 12:36:48','2025-03-08 12:36:48'),
    (6,'12edcdbd-5a2c-48be-b612-3e0ac29a9b1f','abctest child 2',1,4,2,1,'App\\Models\\Feed','2025-03-08 12:41:09','2025-03-08 12:41:09');

预期排序效果需按父ID分组展示(如附图所示),但我编写的Laravel Eloquent代码无法实现该需求,请求帮助解决:

当前实现代码

public function replies(): CursorPaginator
{
    $comments = Comment::with([
        'user', 
        'photos', 
        'depthComment', 
        'comment', 
        'commentCount'
    ]);
    
    if ($this->models && $this->callable) {
        $comments = $comments->whereHasMorph('commentable', $this->models, $this->callable);
    }

    $comments = $comments->whereHas('depthComment', function($query) {
        $query->where('slug', $this->slug);
    });

    $comments = $comments->orderBy('comment_id');
    $comments = $comments->latest();

    return $comments->cursorPaginate(
        config('app.front.pagination_limit')
    );
}

内容的提问来源于stack exchange,提问作者Bahasaweb.com

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 01:14:52