Search code examples
phpmysqlsqlcodeigniter-2

active record in codeigniter in the case of assignment by value


This my model function. obviously it is not best practice to mix sql query and active record together. How should I write the entire function using active record?

public function foo_bar_function($id, $date, $amount) {

       $this->db->where('id', $id);
       $this->db->set('date', $date, TRUE);
       $this->db->set('amount', $amount, FALSE);
       $this->db->update('table_foo');
       $sql = "UPDATE table-foo set diff = total - " . $amount . " WHERE id = '" . $id . "'";
       $this->db->query($sql);
       }

Solution

  • Using active record you can rewrite your update query as below,Also you can use single update instead of running 2 update queries

    public function foo_bar_function($id, $date, $amount) {
        $this->db->set('date', $date);
        $this->db->set('amount', $amount);
        $this->db->set('diff', 'total -'.$amount, FALSE);
        $this->db->where('id', $id);
        $this->db->update('table_foo');
    }
    

    See set() method of active record