phpcodeigniterjoinsql-updatequery-builder

How can I UPDATE Table A in MySQL joining another table?


I have a stats table that has a user_id. I have a users table with an id that corresponds to the above user_id. I also have an employee flag in the users table.

I want to update all records in the stats table where the user_id is not that of an employee.

Ideally, I'd like to do this via the CodeIgniter Active Record, but I'm fine with a raw query as well.

Thanks!

EDIT My attempt

if($employee == false) {
  $this->db->where('(default_profiles.opid = 0 OR default_profiles.opid IS NULL)');  
} else {
  $this->db->where('default_profiles.opid > 0');
}
$this->db->join('weekly_stats', 'default_weekly_stats.user_id = default_profiles.user_id');

$this->db->update('default_weekly_stats', $data);

However, this just yields:

UPDATE `default_weekly_stats` SET `rank` = 1 WHERE `default_weekly_stats`.`week` = '1' AND `default_weekly_stats`.`correct_picks` = '4' AND (default_profiles.opid = 0 OR default_profiles.opid IS NULL)

Solution

  • Haven't tried it but maybe it should be like this:

    $this->db->where_not_in('users.employee_flag', '0')->join('users', 'users.user_id = stats.user_id')->update('stats', $data);
    

    EDIT: ( based on @dianuj answer )

    $this->db->set('rank', $rank );
    if($employee == false) {
      $this->db->where('(default_profiles.opid = 0 OR default_profiles.opid IS NULL)');  
    } else {
      $this->db->where('default_profiles.opid > 0');
    }
    $this->db->update('weekly_stats ON default_weekly_stats.user_id = default_profiles.user_id');