我的表结构:
boxes (id, boxname)
boxes_items (id, box_id, item_id)
我正在查看SQL日志中的“删除框”操作,并且有点恐惧。
SELECT COUNT(*) AS count FROM boxes Box WHERE Box.id = 191
SELECT BoxesItem.id FROM boxes_items BoxesItem WHERE BoxesItem.box_id = 191
SELECT COUNT(*) AS count FROM boxes_items BoxesItem WHERE BoxesItem.id = 1685
DELETE FROM boxes_items WHERE boxes_items.id = 1685
SELECT COUNT(*) AS count FROM boxes_items BoxesItem WHERE BoxesItem.id = 1686
DELETE FROM boxes_items WHERE boxes_items.id = 1686
-- snip 50 more SELECT & DELETE statements --
SELECT COUNT(*) AS count FROM boxes_items BoxesItem WHERE BoxesItem.id = 1733
DELETE FROM boxes_items WHERE boxes_items.id = 1733
DELETE FROM boxes WHERE boxes.id = 191
这可能是从我能想到的这些表中删除效率最低的方法。我的意思是,它可以替换为:
DELETE FROM boxes WHERE id = 191
DELETE FROM boxes_items WHERE box_id = 191
Cake是否有这样做的原因?如果没有,您是否知道我可以在不破坏核心库的情况下简化程序的任何方式?
以下是相关的代码:
// app/controllers/boxes_controller.php /////////////
public function delete($id = null) {
if ($this->Box->del($id)) {
$this->redirect(array('action'=>'index'));
}
}
// app/models/box.php ///////////////////////////////
class Boxes extends AppModel {
var $hasAndBelongsToMany = array(
'Item'
);
}
// app/models/app_model.php /////////////////////////
class AppModel {
var $actsAs = array('Containable');
var $recursive = -1;
}
答案 0 :(得分:3)
如果你有一个hasMany关系,我假设你可以尝试设置“exclusive”标志:
http://book.cakephp.org/view/82/hasMany
exclusive:当exclusive设置为true时,递归模型删除使用deleteAll()调用执行删除,而不是单独删除每个实体。这大大提高了性能,但可能不适合所有情况。
答案 1 :(得分:2)
不幸的是,Cake就是这样做的。
您可以使用类似粗略的模型覆盖模型中的del()
方法:
function del($id, $cascade = true) {
if ($cascade) {
$this->BoxesItem->deleteAll(array('BoxesItem.box_id' => $id));
}
return parent::del($id, false);
}