testCode
testCode

Reputation: 117

Delete on cascade in Model Laravel with eloquent

I want to delete data through the api but it is showing an error because it is necessary to delete records in the properties table.

SQLSTATE[23000]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server] The DELETE statement conflicted with the REFERENCE constraint "FK_Interests_Properties_User". The conflict occurred in database "CADASTRO", table "dbo.Interests_Properties", column 'interests_user_id'. (SQL: delete from [Interests_User] where [user_id] = 1515626)

I created the model that performs actions on the Interests_Properts table, but when I try to delete the data that has the same interests_user_id, errors are occurring.

InterestsUser.php:

use App\Source\InterestsProperties;
    
class InterestsUser extends Model
{
    protected $connection = 'sql_cadastro';
    protected $table = 'Interests_User';
    protected $primaryKey = 'id';

    public $timestamps = false;

    public function properties()
    {
        $this->belongsToMany(InterestsProperties::class, 'foreign_key');
    }

    public static function lgpdInterestsUser($id_user, $action)
    {
        if ($action == 'search') {
            $data = InterestsUser::where('user_id', $id_user)->get();

            if (count($data) > 0) {
                return $data;
            } else {
                return false;
            }
        } elseif ($action == 'delete') {
            $data = InterestsUser::with('properties')->where('user_id', $id_user)->get();

            foreach ($data->properties as $p) $p->delete();

            if ($data > 0) {
                return 'Success Remove.';
            } else {
                return 'Not Found.';
            }
        } else {
            return "Action Incorrect!";
        }
    }
}

InterestsProperties.php

class InterestsProperties extends Model
{
    protected $table = 'Interests_Properties';    
    protected $primaryKey = 'id';

    public $timestamps = false;        
}

The error is occurring when trying to remove with cascade:

Call to undefined method Illuminate\Database\Eloquent\Builder::foreign()

Table Structure

Upvotes: 0

Views: 2521

Answers (1)

Juan Eizmendi
Juan Eizmendi

Reputation: 1134

At DB level, using onDelete: when migrating your InterestsProperties model you'll have a line like

$table->foreignId('foreign_key')

to that add ->onDelete('cascade') after that update each time you delete a record from the main table it will do it in this one to.

At PHP level,

$data = InterestsUser::with('properties')->where('user_id', $id_user)->first();
foreach($data->properties as $p) $p->delete();

PD: Those will remove the property record too.

Upvotes: 2

Related Questions