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

标签 php sql-server laravel laravel-5

我正在尝试使用 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/

相关文章:

c# - 在 .Net 核心 2 中使用 SQL Server 文件流

sql - 如何减去总和的负值?

laravel - View Composer 使用通配符 * 在所有 View 中加载变量 laravel 5

使用 bCrypt 哈希密码登录 PHP

sql-server - SSRS 报告管理器未正确显示

php 和 mysql - 插入有效但更新无效

php - Laravel 路线,具有 1 个必需参数和可选的无限参数

laravel - 为什么我的Laravel 5.2事件在本地工作时不能在生产中工作?

php - 如何使用 Android 中的 HTTP 将 Android 中 SQLite 数据库中存储的数据发送到 PHP Web 服务器

php - 尝试身份验证代码交换时身份验证后出现 auth0 401 错误