9

I saw this on the codeigniter forum

Considering the below code

UPDATE a
INNER JOIN b USING (id)
SET a.firstname='Pekka', a.lastname='Kuronen',
b.companyname='Suomi Oy',b.companyaddress='Mannerheimtie 123, Helsinki Suomi'
WHERE a.id=1; 

This is how you would apparently do it in Codeigniter

$this->db->set('a.firstname', 'Pekka');
$this->db->set('a.lastname', 'Kuronen');
$this->db->set('b.companyname', 'Suomi Oy');
$this->db->set('b.companyaddress', 'Mannerheimtie 123, Helsinki Suomi');
$this->db->where('a.id', 1);
$this->db->join('table2 as b', 'a.id = b.id');
$this->db->update('table as a');

this does not work in reality. I have had a look a the SQL which this produces and the results do not even mention the join.

Does anyone have any idea how to do an update with a join using Codeigniter's Active Record Database Class?

2 Answers 2

13

One solution I have found is to remove the join altogether and move the join condition into a 'where' function, also you will need to change the update string to include the new table.

$this->db->set('a.firstname', 'Pekka');
$this->db->set('a.lastname', 'Kuronen');
$this->db->set('b.companyname', 'Suomi Oy');
$this->db->set('b.companyaddress', 'Mannerheimtie 123, Helsinki Suomi');

$this->db->where('a.id', 1);
$this->db->where('a.id = b.id');
$this->db->update('table as a, table2 as b');
1
  • 1
    I thought I would save someone some time. You need to use the "table as a" otherwise CodeIgniter tries to escape the tables and it fails.
    – Eric Cope
    Jun 1, 2013 at 5:40
4

Using two separate queries within a transaction should solve your problem. If a query fails the other one gets rolled back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.