按道理在SQL我们可以从表中删除数据使用连接如
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;
什么将是笨相当于上述查询的?
笨是否支持删除与联接查询?
你必须使用活动记录 ?
这下面的查询将不这样做。
$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));
你不能做到这一点与CodeIgniter的Active Record的类。 它不支持联接在删除查询。 你必须执行使用查询$this->db->query()
由罗宾Castlin提及。
下面的代码从核心文件拍摄。 它是内组成部分之一,其产生的DELETE
查询。
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;
}
正如你所看到的,没有什么在那里,它指定插入JOIN
子句。
我有同样的问题,该连接被忽略:
$r1 = $db->where("object2_type", $object_type)
->join($object_type, "$object_type.id = object1_id", "LEFT")
->where("$object_type.id IS NULL", null, false)
->delete("knots");
所以我做了这样的:
$ids = $db->select("knots.id")
->where("object2_type", $object_type)
->join($object_type, "$object_type.id = object1_id", "LEFT")
->where("$object_type.id IS NULL", null, false)
->get("knots")->result_object();
/* my ow function which generates a string like '1','2','3' or 0 */
$ids_csv = $this->mh()->get_flat_items_as_csv($ids);
$r = $db->where("knots.id IN ($ids_csv)", null, false)->delete("knots);
不是重写整个SQL的,你可以这样做:
// build query as usual...
$this->db
->from ('cookies')
->join ('recipes', 'recipes.cookie = cookies.id')
->where ('recipes.rating', 'BAD');
/*
* get the original DELETE SQL, in our case:
* "DELETE FROM `cookies` JOIN `recipes` ON `recipes`.`cookie`=`cookies`.`id` WHERE `recipes`.`rating`='BAD'"
*/
$sql = $this->db->get_compiled_delete ('cookies');
/*
* insert the target table in the SQL string, to get this:
* "DELETE `cookies` FROM `cookies` JOIN `recipes` ON `recipes`.`cookie`=`cookies`.`id` WHERE `recipes`.`rating`='BAD'"
*/
$target = $this->db->escape_identifiers ('cookies'); // just to be safe
$sql = substr_replace ($sql, " $target", 6, 0); // note the prepended space
// now we can run the query
$q = $this->db->query ($sql);
这样一来,你留着好东西从查询生成器(又名活动记录),并有你定制的自由度也。 我认为,这是相当安全的,因为在$sql
字符串总是以DELETE
。 你可以用这个为功能的快捷方式,当然。