php - laravel 中的更新方法将在数据库中创建一个新模型

标签 php laravel api

我在构建 laravel restful api 时遇到问题,

我有以下 Controller

 <?php
 namespace App\Http\Controllers\Kittrans;
 use App\Http\Controllers\Controller;
 use App\Inventory;
 use App\Kittrans;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\DB;

 class KittransController extends Controller
 {

 public function index()
 {

 }
/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    //
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{

     $rules =[
    'kmo_id' => 'required',
    'item_id' => 'required|integer|min:1',
    'store_id' => 'required|integer|min:1',
    'count' => 'required|integer|min:1'
    ];

    $this->validate($request,$rules);

    // check if requested count of item less than or equal to count in store
    $inventory = DB::table('inventories')->where(
        [
        ['item_id','=',$request->input('item_id')],
        ['store_id','=',$request->input('store_id')]
        ]
        )->get();

    if($inventory->count()!=1)
    {
         return response()->json(['Error'=>'Model not found'],404);
    }

    $remaining = $inventory->get(0)->count;

    if($request->input('count') > $remaining)
    {
        return response()->json(['Error'=>'Request item count should be less than in the selected store!'],422);
    }


    // get user id bu auth. but for now i will make it static to complete first version of api 
    testing
    $request['user_id'] = 1;
    $newModel = Kittrans::create($request->all());

    $remaining = $remaining - $request->input('count');
    Inventory::where('id',$inventory->get(0)->id)->update(array('count' => $remaining));

    return response()->json($newModel,200);

}

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show(Kittrans $kittrans)
{
    //
    return response()->json($kittrans,200);
}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function edit($id)
{
    //
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, Kittrans $kittrans)
{

    $kittrans->fill($request->only([
        'item_id',
        'kmo_id',
        'count'
        ]));

    if($kittrans->isClean())
    {
        return response()->json(['Error'=>'You should make some changes in your values to update'],422);
    }

    $kittrans->save();
    return response()->json($kittrans,200);
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy(Kittrans $kittrans)
{
    //

 $kittrans->delete();

 return response()->json($kittrans,200);
}
}

和 route/api.php 如下:

Route::resource('kittrans','Kittrans\KittransController',['except'=>['index']]);

当我请求更新数据库中的对象时,问题是一个新模型将使用 $kittrans->save() 方法插入到表中!!

为什么会出现这个问题?

我从 postman 那里收到的请求是这样的:

网址:myApp.test/kittrans/5003

方法:放置、修补

内容类型:应用程序/x-www-form-urlencoded

数据:item_id,kmo_id,count

我也添加了 dd($kittrans); 在 save() 方法之前,我得到了以下内容:

Kittrans {#345
#fillable: array:4 [
0 => "count"
1 => "kmo_id"
2 => "item_id"
3 => "user_id"
]
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: array:3 [
"item_id" => "1"
"kmo_id" => "1"
"count" => "7"
]
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [
0 => "*"
]
}

为什么保存方法要在数据库中创建一个新的模型实例? 我已经在所有其他 Controller 中实现了更新方法,一切正常,但是对于这个 Controller ,我不明白问题出在哪里?

最佳答案

用于模型绑定(bind)的 Controller 方法的参数命名不正确。

你的路由参数是kittran不是kittrans;资源路由将使用资源的单数名称作为路由参数。您必须为绑定(bind)匹配该名称:

public function update(Request $request, Kittrans $kittran)

如果没有匹配项,您只会注入(inject)一个新的模型实例,而不是发生模型绑定(bind)。

您可以运行 route:list 命令来查看您的路由是如何定义的:

php artisan route:list

"Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name." - Laravel 6.x Docs - Routing - Route Model Bindings - Implicit Binding

"By default, Route::resource will create the route parameters for your resource routes based on the "singularized" version of the resource name." - Laravel 6.x Docs - Controllers - Resource Controllers - Naming Resource Route Parameters

如果你想为这个资源覆盖这个行为,并使用 kittrans 作为参数名,你也可以这样做,那么你不需要改变你的 Controller 方法的签名:

Route::resource('kittrans', 'Kittrans\KittransController', [
    'except'=> ['index'],
    'parameters' => ['kittrans' => 'kittrans'],
]);

关于php - laravel 中的更新方法将在数据库中创建一个新模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59059401/

相关文章:

php - 从文本到数组的坐标 [preg_match]

Laravel 中的 MySQL 子查询,如何连接查询并将第二个查询的结果作为新列添加到第一个查询?

php - laravel 方法 "inRandomOrder()"真的是随机的吗?

asp.net - 无法在本地使用 windows live api

ruby - Sinatra 构建 REST API 文档

php - 重用学说实体管理器使用的数据库连接

php - PDO fetchall 查询,显示多个结果,但每个 ID 仅显示 1 个结果

php - phpmyadmin插入数据时插入空白记录

laravel - Laravel 中 pluck() 和 list() 的区别?

api - net.Socket.writable、net.Socket.readable 属性不是官方 node.js API 的一部分