【问题标题】:how can i make laravel api show by string value如何让 laravel api 按字符串值显示
【发布时间】:2021-03-18 18:48:40
【问题描述】:

尝试为支付脚本构建 API。但我想使用 API 按 $merchant_id 或 $reference number 显示。但是当我尝试使用 json 时,只返回 $id 这是主键。

如何让它显示为 $merchant_id 字符串?

这是 UserController 中的代码

public function show($merchant_key)
{
    return Exttransfer::find($merchant_key);
    
 
}

以及App/Api中的代码

Route::get('Exttransfer/{$merchant_key}', 'UserController@show');

无论我做什么,它都只通过 $id 显示 Mercer_key 的一个例子是 ) OBGDTE36B2

【问题讨论】:

  • 你能展示Exttransfer的模型吗?

标签: laravel api


【解决方案1】:

由于 find() 通过其主键检索模型,因此 Laravel 将 $merchant_key 视为 id。 试试这个

发件人:

public function show($merchant_key)
{
    return Exttransfer::find($merchant_key);
}

收件人:

public function show($merchant_key)
{
    return Exttransfer::where('merchant_key',$merchant_key)->get();
}

如果您想获得单个记录,请使用 first() 而不是 get()

Read More about find()

【讨论】:

  • 只有当我使用路由 Route::resource('Exttransfer', 'UserController'); 而不是 Route::get('Exttransfer/{$merchant_key}', 'UserController@show'); 时它才会显示。我怎样才能返回基于 $merchant_key 和 $referencenumber ,而不仅仅是 $merchant_key
  • 我强烈建议使用first() 而不是get()
【解决方案2】:

根据雄辩的文档:

#find($key)

find 方法返回具有与给定键匹配的主键的模型。如果 $key 是模型实例,find 将尝试 返回与主键匹配的模型。如果 $key 是一个数组 键,find 将返回所有具有主键的模型 给定数组

所以你应该使用类似return Exttransfer::where('merchant_key', $merchant_key)->first();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-20
    • 2010-10-25
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2013-05-19
    • 2016-03-03
    • 2018-12-17
    相关资源
    最近更新 更多