首页 > 解决方案 > 在模型 Laravel 中使用 eloquent 在级联上删除

问题描述

我想通过api删除数据但它显示错误,因为需要删除属性表中的记录。

SQLSTATE[23000]:[Microsoft][ODBC Driver 17 for SQL Server][SQL Server] DELETE 语句与 REFERENCE 约束“FK_Interests_Properties_User”冲突。冲突发生在数据库“CADASTRO”、表“dbo.Interests_Properties”、列“interests_user_id”中。(SQL:从 [Interests_User] 中删除 [user_id] = 1515626)

我创建了对表执行操作的模型Interests_Properts,但是当我尝试删除具有相同 的数据时,interests_user_id会发生错误。

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

尝试使用级联删除时发生错误:

调用未定义的方法 Illuminate\Database\Eloquent\Builder::foreign()

表结构

标签: sql-serverlaravel

解决方案


在数据库级别,使用onDelete:迁移InterestsProperties模型时,您将有一行

$table->foreignId('foreign_key')

每次您从主表中删除一条记录时,在该更新之后添加->onDelete('cascade') 该记录,它将在该表中执行此操作。

在 PHP 级别,

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

PD:这些也会删除财产记录。


推荐阅读