[英]Laravel apiResource to fetch record by field other than id
我正在使用 Laravel 从我创建了 apiResource controller 的数据库中获取记录。 我在路由中设置了以下代码。
Route::apiResource('/MyController',MyController::class)->middleware('auth:api');
在 MyController.php 我显示特定数据的代码是:
/**
* Display the specified resource.
*
* @param \App\Models\ContentType $contentType
* @return \Illuminate\Http\Response
*/
public function show(MyModel $Model)
{
// show content type info
return response([
'data' => new MyControllerResource($Model)
],200);
}
当我像这样进行 api 调用时,我得到了数据:
http://localhost:8000/api/MyController/1
我想要的是通过在路由中传递其他字段值而不是 id 来获取记录。 例如。
http://localhost:8000/api/MyController/mypost
知道如何实现这一目标吗?
您正在使用路由 model 绑定。 而在 laravel 中,它的默认行为是查找具有id
和返回集合的 model。 它不会搜索任何其他字段。 当然,您可以更改此行为,但它只能按一个字段搜索数据。 要更改此行为,请使用 model 中的getRouteKeyName
方法,例如:
public function getRouteKeyName()
{
return 'another_field_in_my_table';
}
您还可以使用显式绑定,例如:
Route::bind('MyController', function($value) {
return \App\MyModel::where('id', $value)->orWhere('another_field_in_my_table', $value)->first();
});
要了解有关显式绑定检查文档的更多信息。
所有模型的路由键名称默认为id
。 您将希望通过添加getRouteKeyName()
方法将其更新为name
或任何字段“mypost”。
<?php
namespace App;
...
class Post extends Model
{
public function getRouteKeyName()
{
return 'name';
}
...
}
您必须单独定义路线。 您可以按 controller 和中间件对路由进行分组。 完成后,在您的路线内,您需要更改为:
Route::get('/show/{post:columnName}', [ MyController::class, 'show' ])->middleware('auth:api');
现在,您的数据将根据您在路线中定义的列名来获取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.