CodeIgniter- active record insert if new or update on duplicate

前端 未结 8 766
醉酒成梦
醉酒成梦 2020-12-29 04:46

Is it possible to do an active record query in CodeIgniter that will update an existing record if one already exists or insert if it doesnt, for the given k

8条回答
  •  滥情空心
    2020-12-29 05:40

    I doesn't know Codeigniter Active Record Class has this method or not check the codeigniter docs for the methods containing in active record class

    But you can achive this throug extending core models of codigniter. By using this way you can use this method for all the models which extends this model class. Just place the MY_model.php into application/core/ and write the following code.

    Class MY_Model extends CI_Model
    {
      public function insert_update($data)
      {
           // code for checking existing record.
           if(//existing record)
               fire the update query
           else
               fire the insert query
    
           return insert/update id;
    
      }
    }
    

    after creating the above file You have to change the All your models parent class to the new Extended model i.e. MY_Model

    class some_model extends MY_Model
    

    NOTE: You have to select the primary key from results and put it into the where condition.

    It's very critical so what I do when I get the data from the controller I just check it have the ID or not if Id is present then I fired the update query if not then I fired The Insert Query.

    BEST OF LUCK

提交回复
热议问题