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

Laravel 10中通过GET请求基于bookId从MySQL获取评论列表

Laravel API 根据bookId获取书籍评论问题排查与修复

1. 确认模型关联配置

首先确保Book和Comment模型的关联关系正确:

  • Comment模型(假设表名为comments,需包含book_id字段):
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Comment extends Model
{
    protected $fillable = ['content', 'book_id']; // 按需添加其他字段

    public function book(): BelongsTo
    {
        return $this->belongsTo(Book::class, 'book_id');
    }
}
  • Book模型:
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Book extends Model
{
    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class, 'book_id');
    }
}

2. 修正API路由

确保路由定义为GET请求,参数名与控制器接收逻辑匹配:

// routes/api.php
use App\Http\Controllers\CommentController;

// 路由参数传参方式
Route::get('/books/{bookId}/comments', [CommentController::class, 'show']);

// 或QueryString传参方式
// Route::get('/comments', [CommentController::class, 'show']);

3. 修复控制器show方法

根据路由类型选择对应实现:

方式一:路由参数传递bookId

namespace App\Http\Controllers;

use App\Models\Book;
use Illuminate\Http\JsonResponse;

class CommentController extends Controller
{
    public function show(string $bookId): JsonResponse
    {
        // 通过Book模型关联获取评论
        $book = Book::findOrFail($bookId);
        $comments = $book->comments;

        // 或直接查询Comment模型
        // $comments = \App\Models\Comment::where('book_id', $bookId)->get();

        return response()->json([
            'status' => 'success',
            'count' => $comments->count(),
            'data' => $comments
        ]);
    }
}

方式二:QueryString传递bookId(如/api/comments?bookId=cm123)

public function show(): JsonResponse
{
    $bookId = request()->query('bookId');
    if (!$bookId) {
        return response()->json(['status' => 'error', 'message' => 'bookId参数缺失'], 400);
    }

    $comments = \App\Models\Comment::where('book_id', $bookId)->get();
    return response()->json([
        'status' => 'success',
        'count' => $comments->count(),
        'data' => $comments
    ]);
}

4. Postman测试步骤

  • 选择请求方法为GET
  • 输入对应接口地址:
    • 路由参数方式:http://你的域名/api/books/cm123/comments
    • QueryString方式:http://你的域名/api/comments?bookId=cm123
  • 发送请求,验证返回的JSON数据是否包含对应bookId的7条评论

内容的提问来源于stack exchange,提问作者SplashyTechs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:16:30