sql-server - 在模型 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()
表结构
Interests_User
id
interest_id
user_id
created_at
updated_at
Interests_Properties
id
interests_user_id
key
value
created_at
updated_at
解决方案
在数据库级别,使用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:这些也会删除财产记录。
推荐阅读
- javascript - 如何在自定义格式标题与新行之间正则表达式文本?
- discord.py - 升级时添加角色
- python - 在python中查找丢失的数字
- javascript - 在打印 pdf 表格分解和计算时
- powershell - Powershell 变量超过 azure devops 变量
- python - Python蓝牙广告
- postgresql - Prometheus postgres 导出器未显示带有单引号的间隔时间的指标
- r - 通过ggplot中连续变量的中位数重新排序因子水平
- angular - 在 Angular 中正确重置模板驱动的表单
- laravel-8 - 如何通过使用 tinymce wiris 插件获取图像 url?