我对 PHP 和 laravel 相当陌生,所以寻求一些帮助。
例如,我在 mySQL 数据库中有一个表,用于存储用户的评论。该表的值为 userId、bookId 和 Comment。我本质上想在我的控制器中构建一个函数,它将检索特定 bookId 的评论列表。因此,如果 bookId 'cm123' 对该书总共有 7 条评论,那么我的函数应该使用 HTTP GET 请求检索所有 7 条评论。该路由严格进入 API 路由,我们没有为此使用任何视图,因此不需要表单等输入 - 而是在 Postman 中测试请求时手动输入参数。
再次强调,我想要的最终结果是,给定特定的 bookId 输入,API 返回存储在数据库中的图书评论列表
下面是我的模型、路线和控制器类(我已经有一个名为“SHOW”的函数,但它不起作用):
控制器
<?php
namespace App\Http\Controllers;
use App\Models\CreateComment;
use App\Models\BookRating;
use Illuminate\Http\Request;
class BookRatingController extends Controller
{
/**
* Display the specified resource.
*/
public function show(string $bookId): View
{
return view('CreateComment.Comment', [
'Comment' => CreateComment::findOrFail($bookId)
]);
} // return list of comments
型号
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CreateComment extends Model
{
use HasFactory;
protected $fillable =
[
'Comment',
'userId',
'bookId'
];
}
路线
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookRatingController;
use App\Http\Models\BookRating;
use App\Http\Models\CreateComment;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('CreateRating',[BookRatingController::class, 'CreateRating']);//adding a bookrating to database API -- POST METHOD--
Route::post('CreateComment',[BookRatingController::class, 'CreateComment']);
Route::get('show/{$bookId}',[BookRatingController::class,'show']);
要实现上述功能,首先在routes/api.php中创建如下路由
use App\Http\Controllers\CommentController;
Route::get('comments/{bookId}', [CommentController::class, 'show']);
然后在CommentController的show函数中修改如下函数
public function show(Request $request, string $bookId)
{
// Retrieve comments based on the provided bookId
$comments = CreateComment::where('bookId', $bookId)->get();
// Check if comments exist for the given bookId
if ($comments->isEmpty()) {
// Return appropriate response if no comments found
return response()->json(['message' => 'No comments found for the specified bookId'], 404);
}
// Return comments as JSON response
return response()->json($comments);
}