Codeigniter active record update statement with a join

11,665

Solution 1

How about the solution below? A bit ugly but it achieved what you expected in your question.

$invoiceId = 13;
$amount = 4;
$data = array('cd.amount'=>$amount, 'cd.amount_verified'=>'1');

$this->db->where('i.invoice_id', $invoiceId);

$this->db->update('Customer_donations cd join Invoices i on i.cd_id = cd.cd_id', $data);

Solution 2

Even cleaner, since update accepts a third "where" array parameter:

$invoiceId = 13;
$amount = 4;
$data = array('cd.amount'=>$amount, 'cd.amount_verified'=>'1');
$this->db->update('Customer_donations cd join Invoices i on i.cd_id = cd.cd_id', 
  $data, array('i.invoice_id' => $invoiceId));
Share:
11,665
Catfish
Author by

Catfish

Old enough to party. Nerdy by nature. Codementor Blog

Updated on July 01, 2022

Comments

  • Catfish
    Catfish almost 2 years

    This is the query that i'm trying to achieve via active record:

    UPDATE `Customer_donations` cd 
    join Invoices i on i.cd_id = cd.cd_id 
    set cd.amount = '4', cd.amount_verified = '1' 
    WHERE i.invoice_id =  '13';
    

    This is my attempt at the active record:

    $data = array('cd.amount'=>$amount, 'cd.amount_verified'=>'1');
    $this->db->join('Invoices i', 'i.cd_id = cd.cd_id')
         ->where('i.invoice_id', $invoiceId);
    
    
    // update the table with the new data
    if($this->db->update('Customer_donations cd', $data)) {
      return true;
    }
    

    And this is the query that's actually getting produced:

    UPDATE `Customer_donations` cd 
    SET `cd`.`amount` = '1', `cd`.`amount_verified` = '1' 
    WHERE `i`.`invoice_id` =  '13'
    

    Why is this active record statement not applying my join clause?