简体   繁体   English

Laravel删除功能不起作用

[英]Laravel Delete function not work

First project on laravel : When I am going to delete row it throws an Error : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails. laravel上的第一个项目:当我要删除行时,将引发错误:SQLSTATE [23000]:违反完整性约束:1451无法删除或更新父行:外键约束失败。 My controller function 我的控制器功能

 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')
        ]);
}

Model : 型号:

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();
    });
}

Error in detail : 详细错误:

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) SQLSTATE [23000]:完整性约束违规:1451无法删除或更新父行,外键约束失败( red_carpetmedia ,约束media_gallery_id_foreign外键( gallery_id )参考文献galleriesid ))(SQL:从删除galleries那里galleriessource_id = 2和galleriessource_id不是null, galleriessource_type =应用\\地点)

Schema of table : 表的模式:

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');
    });

If you are deleting items from one table that are linked with the other table, then it gives you this error. 如果要从一个表中删除与另一个表链接的项目,则会出现此错误。

If you are using a pivot table, then use onDelete('cascade') like, 如果您使用的是数据透视表,请使用onDelete('cascade')之类的方法,

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

Ref : 参考

你可以加

  onDelete('cascade')

在您的表中,例如:

$table->foreign('user_id') ->references('id')->on('users') ->onDelete('cascade');

Go to your gallery migration file inside database/migrations/examplegallerytable.php and update the relationship definition to these: 转到database/migrations/examplegallerytable.php图库迁移文件,并将关系定义更新为以下内容:

$table->foreign('media_id')->references('id')->on('medias')->onDelete('cascade');

then run these command: 然后运行以下命令:

php artisan migrate:reset

and

php artisan migrate

that's all 就这样

As others have suggested, you can use onDelete method to prevent the error. 正如其他人所建议的那样,您可以使用onDelete方法来防止该错误。 But I dont recommend to actually delete your records in the database. 但是我不建议您实际delete数据库中的记录。

You can use SoftDeletes to delete records by adding a deleted_at timestamp field to your table schema. 通过将deleted_at时间戳字段添加到表架构中,可以使用SoftDeletes删除记录。 Then all your queries will only fetch rows where deleted_at IS null 然后,您所有的查询将仅获取deleted_at IS null

To enable this in your models, make sure that your tables has $table->softDeletes() . 要在模型中启用此功能,请确保您的表具有$table->softDeletes() This will add the necessary deleted_at field to your tables. 这会将必要的deleted_at字段添加到表中。

Next, add the Illuminate\\Database\\Eloquent\\SoftDeletes trait to your models like this. 接下来,将Illuminate\\Database\\Eloquent\\SoftDeletes特性添加到您的模型中。

use Illuminate\Database\Eloquent\Model; 
use Illuminate\Database\Eloquent\SoftDeletes; 

class Foo extends Model { 
    use SoftDeletes; 
}

Aaannd, that's it! Aaannd,就是这样! Every time you perform a query with Foo , all non-null deleted_at value will be ignored. 每次使用Foo执行查询时,所有non-null delete_at值都将被忽略。

$foos = Foo::all();

And whenever you perform delete() , it will simply update deleted_at to the current timestamp. 并且无论何时执行delete() ,它deleted_at更新为当前时间戳。

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

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