【问题标题】:How to update multiple rows sharing same foreign key in Codeigniter如何在 Codeigniter 中更新共享相同外键的多行
【发布时间】:2022-01-23 11:49:14
【问题描述】:

我有 2 张桌子; db_file_acess and db_file_access_details。我在db_file_access_details 表中有一个列subjects_id。从 UI 中,我可以选择几个带有其他详细信息的主题 [array] 并将它们插入到 db_file_acess 表中,并将 subject_ids 插入到 db_file_access_details 中。插入没问题,但是当我更新这两个表时,我似乎无法更新所有行。这是我的更新查询

$result = array();
        foreach ($subject_id as $key => $val) {
            $result[] = array(
                'file_access_id' =>$q_id,
                'subjects_id' => $_POST['subject_id'][$key]
            );
        }
        $this->db->update_batch('db_file_access_details', $result, 'file_access_id');

查询运行,但它只更新了一个 id,如下面的屏幕截图所示:

result() 数组如下共享:

Array
(
    [0] => Array
        (
            [file_access_id] => 45
            [subjects_id] => 1
        )

    [1] => Array
        (
            [file_access_id] => 45
            [subjects_id] => 3
        )

    [2] => Array
        (
            [file_access_id] => 45
            [subjects_id] => 4
        )

)

update_batch查询后,结果如下图 我做错了什么?

【问题讨论】:

    标签: codeigniter


    【解决方案1】:

    根据文档update_batch('db_file_access_details', $result, 'file_access_id') 产生:

    UPDATE `db_file_access_details` SET `subjects_id` = CASE
    WHEN `file_access_id` = 45 THEN 1
    WHEN `file_access_id` = 45 THEN 3
    WHEN `file_access_id` = 45 THEN 4
    ELSE `subjects_id` END
    WHERE `file_access_id` IN (45, 45, 45)
    

    对于所有三行,第一个 case 匹配,因此所有 subject_ids 都设置为 1。

    要使 update_batch 正常工作,您需要使用 id 列。

    根据您想要实现的目标,您还可以考虑删除db_file_access_detailsfile_access_id 的所有行,然后使用insert_batch 插入$result 数组。

    【讨论】:

    • 一个很好的解决方案。没想到这一点。通过删除所有行然后重新批量重新插入数据解决了我的问题,感谢@Marleen
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多