我有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
正如你所看到的,我想再添加一个类别ID为4的记录,并删除CartegoryID为3的记录,我想使用这样一个模型:
$this->postCategory_model->update_post_categories($categories);
我只是想不出这种模型方法的正确结构。
寻找一些建议
谢谢!
ok删除旧的比检查现有的然后更新更快
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();
}