gpt4 book ai didi

php - Laravel 删除功能不起作用

转载 作者:行者123 更新时间:2023-12-01 15:45:25 25 4
gpt4 key购买 nike

laravel 上的第一个项目:当我要删除行时,它抛出一个错误:SQLSTATE[23000]:违反完整性约束:1451 无法删除或更新父行:外键约束失败。我的 Controller 功能

 public function delete(Request $request) {
try {
Venue::findOrFail($request->id)->delete();
} catch (\Exception $ex) {
return response()->json([
'error' => $ex->getCode(),
'message' => $ex->getMessage()
]);
}

return response()->json([
'message' => trans('admin.venue.delete_success')
]);
}

型号:

protected static function boot()
{
parent::boot();

self::deleting(function (Venue $venue) {
$venue->occasions()->delete();
$venue->contact()->delete();
$venue->gallery()->delete(); // here i am gtng error
$venue->venueParameter()->delete();
});
}

详细错误:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (red_carpet.media, CONSTRAINT media_gallery_id_foreign FOREIGN KEY (gallery_id) REFERENCES galleries (id)) (SQL: delete from galleries where galleries.source_id = 2 and galleries.source_id is not null and galleries.source_type = App\Venue)

表的架构:

Schema::create('venues', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('client_id');
$table->string('name');
$table->string('logo');
$table->unsignedInteger('venue_type_id');
$table->boolean('is_premium');
$table->boolean('is_verified');
$table->string('tripadvisor_url')->nullable();
$table->enum('status',['Active','Inactive']);
$table->timestamps();

$table->foreign('client_id')->references('id')->on('clients');
$table->foreign('venue_type_id')->references('id')->on('venue_types');
});

Schema::create('galleries', function (Blueprint $table) {
$table->increments('id');
$table->string('source_type');
$table->unsignedInteger('source_id');
$table->string('title');
$table->unsignedInteger('sort_order');
$table->enum('status',['Active','Inactive']);
$table->timestamps();
});
Schema::create('media', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('gallery_id');
$table->enum('type',['Image','Video']);
$table->string('caption');
$table->string('path')->nullable();
$table->string('thumbnail')->nullable();
$table->longText('video_code')->nullable();
$table->boolean('is_banner_image')->default(false);
$table->boolean('is_thumb_image')->default(false);
$table->unsignedInteger('sort_order');
$table->enum('status',['Active','Inactive']);
$table->timestamps();

$table->foreign('gallery_id')->references('id')->on('galleries');
});

最佳答案

如果您从一个表中删除与另一个表链接的项目,则会出现此错误。

如果您使用的是数据透视表,则使用 onDelete('cascade') 之类的,

$table->foreign('foreign_key')->references('primary_key')->on('table_name')->onDelete('cascade');

Ref :

关于php - Laravel 删除功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47626860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com