【发布时间】:2021-11-25 20:08:08
【问题描述】:
我用php artisan make:controller ProductController --resource 创建了一个产品资源控制器。并拥有所有必要的方法:索引、显示、更新和销毁。
我使用的是 Laravel 8,destroy 方法默认使用 Product $product 作为参数(路由模型绑定)。
理论上,我只需要取出产品对象并删除它?我还得到了状态码 200 和一个 true。然而,该条目并未从数据库中删除。
注意:我将路由键名称更改为 ID,将索引键名称更改为 uid 而不是 id。请参阅迁移和模型。
问题:为什么?我缺少什么?跟更改的路由键名有关系吗?
这是我的 ProductController、模型、迁移和路由:
ProductController.php -> destroy() 方法
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Product $product
* @return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$result = $product->delete();
return response()->json([
'status' => $result,
'msg' => $result ? 'success' : 'failed'
]);
}
型号\产品
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'ID',
'name',
'price',
];
public function getRouteKeyName()
{
return 'ID';
}
}
产品迁移 up() 方法
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('uid'); // changed
$table->integer('ID')->unique(); // my new Route Key Name
$table->string('name')->nullable();
$table->integer('price')->nullable();
$table->timestamps();
});
}
路由 api.php
Route::resource('products', App\Http\Controllers\ProductController::class);
【问题讨论】: