Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codeigniter - database : how to update multiple tables with a single update query

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?

like image 226
Mazatec Avatar asked Jan 28 '11 16:01

Mazatec


People also ask

Can we update multiple tables in a single update statement?

1 Answer. It's not possible to update multiple tables in one statement, however, you can use the transaction to make sure that two UPDATE statements must be treated atomically. You can also batch them to avoid a round trip like this. and T1.id = '011008';

Can we update multiple tables using update command?

The short answer to that is no. While you can enter multiple tables in the from clause of an update statement, you can only specify a single table after the update keyword.

How do you update multiple tables in a single query in access?

No. You can't update more than 1 table in a single query. You can, however, put all the updates into a transaction, and commit the transaction at the end of all the updates. For Access SQL an absolute "No" is actually incorrect.


2 Answers

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');
like image 76
Mazatec Avatar answered Oct 22 '22 21:10

Mazatec


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

like image 35
Ian Avatar answered Oct 22 '22 23:10

Ian