使用codeigniter删除并在数据库中插入多个记录 [英] Delete and insert multiple records in database using codeigniter

查看:160
本文介绍了使用codeigniter删除并在数据库中插入多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个项目,无法找出当前问题的解决方案。

I am working on one project and cannot figure out the solution of the current problem.

查看

管理员可以使用复选框为用户分配多个或单个角色,如下图所示:

Admin can assign multiple or single role to user using checkbox as shown in following figure:

现在,当我们点击提交按钮。以下是控制器的功能:

Now, when we hit the submit button. Here is what the controller does:

控制器

        $addRoles['userID']=$uid;
        $addRoles['addDate']=time();

        foreach($this->input->post('roles') as $val)
            {

            $addRoles['roleID']=$val;

            $this->admins->updateRole($addRoles);

            }

它正在成功存储所有数据。在内循环中,我调用模型函数将数据添加到数据库中。

it is successfully storing all the data. Inside loop i call the model function to add data into database.

现在,我想做的是,所有现有的角色必须从数据库中删除,如果当前用户有任何因为它不会允许重复的值。稍后,将所有角色逐个添加到数据库中。这是我的模型代码:

Now, what i want to do is that the all the existing roles must be deleted from database if current user has any because it will not allow duplication of values. Later, add all roles one by one in to the database. Here is my model code:

模型

    function updateRole($role){


    $this->db->where('userID', $role['userID']);
    $this->db->where('roleID', $role['roleID']);

    $this->db->delete('user_roles');
    $this->db->insert('user_roles', $role);
    return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
}



现在,我遇到的问题是,当模型运行删除查询仅当该检查角色已在数据库中时才删除记录。或者如果我只删除用户id,那么它将删除所有的记录每次查询将运行。我不能简单地插入记录,因为我必须更新角色和角色可以在不同的时间分配不同。

Now, the problem I am experiencing is that when model runs the delete query it only deletes the record if that checked role is already in the database. Or if i delete only by user id then it will delete all the records every time query will run. I cannot simply insert records because i have to update the roles and roles can be assigned different at different times.

任何帮助将不胜感激。
感谢

Any help will be appreciated. Thanks

推荐答案

你可以做两个函数
1)saveRoles($ role,$ user_id)
2.)updateRoles($ role,$ user_id)

You can do like by making two functions 1) saveRoles($role, $user_id) 2.)updateRoles($role, $user_id)

function saveRoles($role, $user_id)
{
      // can save roles of user using insert 

}

function updateRoles($role, $user_id)
{
     // delete all existing roles of that user 
     // with only user_id in where clause
     // after that you can call 
     $this->saveRoles($role, $user_id);
}

updateRoles函数将删除所有现有条目并在Db中插入一组新值

The updateRoles function will delete all existing entries and insert new set of values in Db that you want to update.

我希望这可以帮助你!

这篇关于使用codeigniter删除并在数据库中插入多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆