简体   繁体   English

Laravel apiResource 按字段而不是 id 获取记录

[英]Laravel apiResource to fetch record by field other than id

I am using Laravel to fetch records from the database for which I have created an apiResource controller.我正在使用 Laravel 从我创建了 apiResource controller 的数据库中获取记录。 I have setup the following code inside routes.我在路由中设置了以下代码。

Route::apiResource('/MyController',MyController::class)->middleware('auth:api');

In MyController.php my code to display a specific data is:在 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);
    }

I get the data when I place an api call like this:当我像这样进行 api 调用时,我得到了数据:

http://localhost:8000/api/MyController/1

What I want is a record getting fetched by passing other field value instead of id in the route.我想要的是通过在路由中传递其他字段值而不是 id 来获取记录。 For example.例如。

http://localhost:8000/api/MyController/mypost

Any idea how can I achieve this?知道如何实现这一目标吗?

You are using route model binding.您正在使用路由 model 绑定。 And in laravel its default behaviour is to find model with id and return collection.而在 laravel 中,它的默认行为是查找具有id和返回集合的 model。 It will not search for any other field.它不会搜索任何其他字段。 Of course you can change this behaviour but it can only search data by one field.当然,您可以更改此行为,但它只能按一个字段搜索数据。 To change this behaviour use getRouteKeyName method in model like:要更改此行为,请使用 model 中的getRouteKeyName方法,例如:

public function getRouteKeyName()
{
    return 'another_field_in_my_table';
}

You can also use explicit binding like:您还可以使用显式绑定,例如:

Route::bind('MyController', function($value) {
   return \App\MyModel::where('id', $value)->orWhere('another_field_in_my_table', $value)->first();
});

To learn more about explicit binding check docs .要了解有关显式绑定检查文档的更多信息。

The route key name defaults to id for all models.所有模型的路由键名称默认为id You will want to update this to name or whatever field "mypost" is by adding a getRouteKeyName() method.您将希望通过添加getRouteKeyName()方法将其更新为name或任何字段“mypost”。

<?php

namespace App;

...

class Post extends Model
{
    public function getRouteKeyName()
    {
        return 'name';
    }

    ...
}

You'll have to define route separately.您必须单独定义路线。 You can group the routes by controller and middleware though.您可以按 controller 和中间件对路由进行分组。 And once done, then, Inside your route, you need to change to this:完成后,在您的路线内,您需要更改为:

Route::get('/show/{post:columnName}', [ MyController::class, 'show' ])->middleware('auth:api');

Now your data will be fetched on the basis of your column name defined in the route.现在,您的数据将根据您在路线中定义的列名来获取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM