我设置了一个一(过程)对多(工具)关系。有时我想删除与程序相关的所有工具:
class Procedure extends BaseProcedure
{
...
function deleteTools()
{
$aProcedure = $this;
$someCondition = true;
foreach( $aProcedure->getTools() as $tool )
{
if($someCondition) {
$tool->delete();
}
}
$aProcedure->save(); // Right Here!
}
}
class ProcedureActions extends sfActions
{
...
public function executeTest(sfWebRequest $request)
{
$this->procedure = $this->getRoute()->getObject();
$this->procedure->deleteTools();
$this->action = "show";
$this->setTemplate("show", "procedure");
}
}
在这一行,我得到以下错误消息:
"SQLSTATE[23000]:违反完整性约束:1048列'procedure_id'不能为null"。仔细研究,我发现这个sql语句正在准备中。
execute:INSERT INTO procedure_tools(id,procedure_id,tool_id,status_id,itemcount,comment)值(?,?,??,?)-(,)
在我看来,相关程序还不知道这一删除。不过我想不出该怎么绕过这个。删除正在工作。第二次刷新,一切正常。感谢您的帮助。
(1)编辑以澄清更准确地表示我的场景。首先为没有这样做道歉。
(2)编辑以显示整个函数的上下文。那里会有更多的逻辑(特别是评估$someCondition,但目前它总是评估为true)。此外,启动动作的内容也会显示出来,以防我用错误的方式变魔术。
(3)编辑添加,来自showSuccess模板的代码。
<?php foreach($procedure->getTools() as $tool): ?>
<tr>
<td><?php echo $tool->getId() ?></td>
<td><?php echo $tool->getStatus() ?></td>
<td><?php echo $tool->getName() ?></td>
</tr>
<?php endforeach; ?>
为什么不在之后执行所有删除操作?这样,您只需执行一个查询即可删除许多工具。
$toolsToDelete = array();
foreach( $aProcedure->getTools() as $tool )
{
if($someCondition) {
$toolToDelete[] = $tool->getId();
}
}
$aProcedure->save(); // Right Here!
Doctrine_Query::create()
->delete('Tools t')
->whereIn('t.id', $toolsToDelete)
->execute();
编辑:
在你的模板中发生的事情是,Doctrine已经获取了关系Tools
,所以它以某种方式被缓存了。这就是为什么在你的模板中,你仍然有删除的工具,并且没有在页面上重新加载它们。
我不记得我过去是如何做到这一点的,但你可以尝试refresh
对象及其关系。所以不是:
$aProcedure->save(); // Right Here!
尝试:
$aProcedure->refresh(true);
ps:我假设您在deleteTools()
函数中对$aProcedure
不执行任何其他操作。否则,您不应该删除save()
。
foreach
循环不是必需的,很可能是您遇到问题的原因。
$aProcedure->Tools->delete();
完成。