Is it possible to UPDATE a JOINed table using Code

2019-05-07 10:22发布

问题:

Here is what I'd like to do

function edit_save($data, $post_id, $user_id)
{
    $this->db->where('post.user_id', $user_id);
    $this->db->where('post.post_id', $post_id);
    $this->db->join('data', 'post.data_id_fk = data.data_id', 'left');
    $this->db->update('post', $data);
}

The 'post' table needs to be left-joined with 'data'.

When I run the above I get a SQL error saying that one of the fields from the 'data' table is not found.

Any suggestions?

MORE INFO

This is the generated SQL query

UPDATE `post` 
SET `data_value` = '111', `data_date` = '2012-02-13', `post_text` = '111' 
WHERE `post_stream_id` =  '5' 
    AND `post_id` =  '18'

This is the error

Unknown column 'data_value' in 'field list'

It doesn't show the JOIN statement.

回答1:

Try this active record query for update with joins:

function edit_save($data, $post_id, $user_id)
{
    $this->db->set($data)
    $this->db->where('post.user_id', $user_id);
    $this->db->where('post.post_id', $post_id);
    $this->db->where('post.data_id_fk = data.data_id');
    $this->db->update('post, data');
}