【问题标题】:update n n relation mysql codeigniter更新 n n 关系 mysql codeigniter
【发布时间】:2013-07-26 11:09:12
【问题描述】:

我有 PostCategory 表:

CREATE TABLE IF NOT EXISTS `PostCategory` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `PostID` int(11) NOT NULL,
  `CategoryID` int(11) NOT NULL,
  PRIMARY KEY (`ID`)
)

假设我有以下记录:

ID || PostID || CategoryID
===========================
1  ||   1    ||   1
2  ||   1    ||   2
3  ||   1    ||   3
4  ||   2    ||   2

当我需要更新 ID 为 1 的帖子类别时出现问题 现在,如果我更改帖子类别,我会得到这个数组:

$categories = array(1, 2, 4);

我想更新我的表格,使其看起来像这样:

ID || PostID || CategoryID
===========================
1  ||   1    ||   1
2  ||   1    ||   2
4  ||   2    ||   2
5  ||   1    ||   4

如您所见,我想再添加一条 CategoryID 为 4 的记录并删除 CartegoryID 为 3 的记录,我想使用这样的一个模型:

$this->postCategory_model->update_post_categories($categories);

我只是想不出这个模型方法的正确结构。

寻找一些建议

谢谢!

【问题讨论】:

  • 而不是“删除”,也许您可​​以考虑使用默认值为 1 的“活动”标志 - 因此,在运行时,首先将所有标志设置为“0”,然后“重新激活”符合条件的。

标签: mysql codeigniter


【解决方案1】:

删除旧的比检查现有的然后更新更快

function update_post_categories($PostID, $categories) {
    $this->db->trans_start();
    //delete old cats
    $this->db->where('PostID', $PostID);
    $this->db->delete('Posts');
    //insert new ones
    foreach ($categories as $cat) {
        $this->db->set('PostID ', $PostID);
        $this->db->set('CategoryID', $cat);
        $this->db->insert('PostCategory');
    }

    $this->db->trans_complete();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2014-09-12
    • 2023-03-14
    • 1970-01-01
    • 2011-11-08
    • 2012-06-08
    相关资源
    最近更新 更多