无法解决此错误违反完整性约束:1451无法删除或更新父行:外键约束失败

时间:2019-06-10 06:44:19

标签: laravel-5

我想删除一个用户帐户当我在facebook上创建一个帐户并删除facebook帐户时,它可以在简单帐户上正常工作。

  

违反完整性约束:1451无法删除或更新父行:外键约束失败(mood_dbactivities,约束activities_user_id_foreign外部键(user_idusersid))

我进行搜索以解决此问题,但找不到为什么无法删除Facebook帐户。 这是我用于删除帐户的代码。

public function destroy($id)
{
    $user = User::find($id);

    $user->delete();

    return response()->json(['message' => 'User Deleted Succesfully'], 200);

}

这是活动的架构。

class CreateActivitiesTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('activities', function (Blueprint $table) {
        $table->bigInteger('id', true)->unsigned();
        $table->text('activity_type');
        $table->bigInteger('user_id')->unsigned()->index('user_id');
        $table->bigInteger('category_id')->unsigned()->index('category_id');
        $table->bigInteger('subcategory_id')->unsigned()->index('subcategory_id');
        $table->text('activity_privacy');
        $table->integer('activity_privacy_visible')->default(0);
        $table->dateTime('activity_datetime_from');
        $table->dateTime('activity_datetime_to');
        $table->string('activity_address');
        $table->bigInteger('company_id')->unsigned()->nullable()->index('company_id');
        $table->decimal('latitude', 11, 8);
        $table->decimal('longitude', 11, 8);
        $table->integer('age_from');
        $table->integer('age_to');
        $table->string('people_limit')->nullable();
        $table->string('activity_picture')->nullable();
        $table->string('activity_title', 35)->nullable();
        $table->string('activity_description', 1000)->nullable();
        $table->timestamps();

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

        $table->foreign('category_id')
            ->references('id')
            ->on('categories')
            ->onDelete('cascade');

        $table->foreign('subcategory_id')
            ->references('id')
            ->on('subcategories')
            ->onDelete('cascade');

        $table->foreign('company_id')
            ->references('id')
            ->on('companies')
            ->onDelete('cascade');
    });
}

请帮助提前致谢。

1 个答案:

答案 0 :(得分:0)

请为模型文件设置代码。

class User extends Eloquent
{
    public function activities() {
        return $this->has_many('Activity');
    }

    // this is a recommended way to declare event handlers
    public static function boot() {
        parent::boot();

        // before delete call this for child activity records delete
        static::deleting(function($user) { 
             $user->activities()->delete();             
        });
    }
}