Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter deleting data with joins tables

Logically in SQL we can delete data from tables with JOINS e.g.

DELETE  clb_subscriber_group_mapping .* FROM clb_subscriber_group_mapping 
INNER JOIN clb_driver_group ON (clb_driver_group.id = clb_subscriber_group_mapping.driver_group_id)
INNER JOIN clb_company ON (clb_company.id = clb_driver_group.company_id)
WHERE clb_company.id = 256 AND clb_subscriber_group_mapping.subscriber_id = 1784;

What will be the CodeIgniter equivalent of above query?

Does CodeIgniter support Delete query with joins?

like image 504
Jatin Dhoot Avatar asked May 14 '12 10:05

Jatin Dhoot


2 Answers

Do you have to use Active Records?

This below query will do otherwise.

$int_company_id = 256;
$int_subscriber_id = 1784;

$this->db->query("
DELETE  clb_subscriber_group_mapping .* FROM clb_subscriber_group_mapping 
INNER JOIN clb_driver_group ON (clb_driver_group.id = clb_subscriber_group_mapping.driver_group_id)
INNER JOIN clb_company ON (clb_company.id = clb_driver_group.company_id)
WHERE clb_company.id = ? AND clb_subscriber_group_mapping.subscriber_id = ?;

", array($int_company_id, $int_subscriber_id));
like image 165
Robin Castlin Avatar answered Oct 11 '22 22:10

Robin Castlin


You can't do that with CodeIgniter's Active Record class. It doesn't support joins in delete query. You'll have to execute the query using $this->db->query() as mentioned by Robin Castlin.

The below code is taken from the core files. It is one of the inner components, that generates the DELETE query.

function _delete($table, $where = array(), $like = array(), $limit = FALSE)
{
    $conditions = '';

    if (count($where) > 0 OR count($like) > 0)
    {
        $conditions = "\nWHERE ";
        $conditions .= implode("\n", $this->ar_where);

        if (count($where) > 0 && count($like) > 0)
        {
            $conditions .= " AND ";
        }
        $conditions .= implode("\n", $like);
    }

    $limit = ( ! $limit) ? '' : ' LIMIT '.$limit;

    return "DELETE FROM ".$table.$conditions.$limit;
}

As you can see, there's nothing in there that specifies the insertion of a JOIN clause.

like image 37
Kemal Fadillah Avatar answered Oct 11 '22 23:10

Kemal Fadillah