gpt4 book ai didi

php - 如何在 laravel 5.7 中删除 3 个关系表中的数据

转载 作者:可可西里 更新时间:2023-11-01 00:54:18 24 4
gpt4 key购买 nike

我正在尝试使用 laravel 5.7 删除 3 个关系表上的数据,当我在 2 个关系表上尝试它时,它运行良好,但是当我在 3 个关系表中尝试它时,它不起作用。

这是我的 table 的样子:

表 1:group_access

|----|------------|| id | group_name ||----|------------|| 67 |     test   ||----|------------|

table 2 : fa_group_access

|----|-----------------|--------|| id | group_access_id | name   ||----|-----------------|--------||  1 |     67          | john   ||----|-----------------|--------|

table 3 : survey_group_access

|----|-----------------|---------------|| id | group_access_id | code_survey   ||----|-----------------|---------------||  1 |     67          | SF-001        ||----|-----------------|---------------|

and this is my function in the controller to delete the data:

public function destroy($id)
{
$group = Groups::findOrFail($id);

if($group->delete())
{
Survey_group_access::where('group_access_id', $id)->get();
FA_Group_Access::where('group_access_id', $id)->get();
return response()->json(['status'=>'success']);
}
}

我得到了这样的错误 sql:

SQLSTATE[23000]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]The DELETE statement conflicted with the REFERENCE constraint "survey_group_access_group_access_id_foreign". The conflict occurred in database "aetra2", table "dbo.survey_group_access", column 'group_access_id'. (SQL: delete from [group_access] where [id] = 67)

如何修复这个错误?

最佳答案

在 group_access 模型中定义关系

public function fa_group_access()
{
return $this->hasMany('fa_group_access');
}

public function survey_group_access()
{
return $this->hasMany('survey_group_access');
}

删除记录及相关:

$group_access = Group_access::find($id);

// delete related
$group_access->fa_group_access()->delete();
$group_access->survey_group_access()->delete();

$group_access->delete();

I don't test the code may be there is syntax error but it should be some thing like this.

希望对你有帮助

关于php - 如何在 laravel 5.7 中删除 3 个关系表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54414962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com