Delete a row WITHOUT cascade

Posted 1 year ago by priverop

Hello,

I have a simple one to many relationships between Part and Presupuesto. A Presupuesto can have many Parts.

When I deleted a Part I also got the Presupuesto deleted, which I don't want. I removed the ->onDelete('cascade') but I have a Integrity constraint violation:

 local.ERROR: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`bbdd`.`parts`, CONSTRAINT `parts_presupuesto_id_foreign` FOREIGN KEY (`presupuesto_id`) REFERENCES `presupuestos` (`id`)) (SQL: delete from `presupuestos` where `id` = 2) {"exception":"[object] (Illuminate\Database\QueryException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`bbdd`.`parts`, CONSTRAINT `parts_presupuesto_id_foreign` FOREIGN KEY (`presupuesto_id`) REFERENCES `presupuestos` (`id`)) (SQL: delete from `presupuestos` where `id` = 2) at /Applications/XAMPP/xamppfiles/htdocs/modifase-v2/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, PDOException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`bbdd`.`parts`, CONSTRAINT `parts_presupuesto_id_foreign` FOREIGN KEY (`presupuesto_id`) REFERENCES `presupuestos` (`id`)) at /.../vendor/laravel/framework/src/Illuminate/Database/Connection.php:483)

PART MIGRATION

public function up()
    {
        Schema::create('parts', function (Blueprint $table) {
            $table->increments('id')->unsigned()->unique();
            $table->string('name');
            $table->integer('presupuesto_id')->unsigned();
            $table->foreign('presupuesto_id')->references('id')->on('presupuestos');
            $table->timestamps();
        });
    }

PART CONTROLLER

public function destroy($id)
    {
      
      $part = Part::find($id)->delete();

      return response()->json($part);
    }

PART MODEL

public function presupuesto(){
    return $this->belongsTo('App\Presupuesto');
  }
protected $fillable = [

        'name', 'presupuesto_id'

    ];

What should I do?

Thanks!

EDIT: I just found the issue. In my AJAX request I wasn't getting the URL:

var form_action = $(element).next().val();
  console.log(form_action); // THIS WAS EMPTY
  $.ajax({
      dataType: 'json',
      type: 'DELETE',
      url: form_action
  }).done(function(data){
      location.reload();
  });

So it seems like the ajax was requesting a DELETE in the current url of the app (presupuesto/1), and it deletes the presupuesto and the part.

Please sign in or create an account to participate in this conversation.