【发布时间】:2012-04-13 06:24:18
【问题描述】:
此代码仅更新一行(与数组中第一行匹配的行):
编辑:显示更多代码!
这是我的看法。它基于关联(有一个模型“客户端”与其他两个模型,程序和用户具有一对多关系)来获取数据库条目。
<div class="view">
<h2><?php echo h($program['Program']['title'])?></h1>
<?php echo $this->Form->create('User', array('action' => 'pushing')); ?>
<table id="pushTable">
<tr><th colspan="5">Select the athletes you would like to push this program to:</th></tr>
<tr>
<?php $i=0; ?>
<?php foreach ($clients['Players'] as $player) {?>
<?php if ($i == 0) {?><tr><?php } ?>
<td><?php echo $this->Form->checkbox($player['id']) . ' ' . $player['username'];?></td>
<?php if ($i == 4) {?></tr><?php $i = 0; } else { $i++; } ?>
<?php } ?>
</tr>
</table>
<?php echo $this->Form->end(__('Push')); ?>
</div>
在我的用户控制器中:
public function pushing() {
if ($this->request->is('post') || $this->request->is('put')) {
$athletes = $this->request->data['User'];
foreach ( $athletes as $player => $flag){
if ($flag == 0){
unset($athletes[$player]);
}
}
$this->User->updateAll(
array('User.data' => "'foo'"),
array('User.id' => $athletes)
);
$this->Session->setFlash(__('Programs were pushed!'));
}
}
}
$athletes 是从复选框中收集的数组,在我看来这没有问题...所以我不确定为什么 updateAll 没有遍历数组中的每个 ID...
也许由于与数据库相关的原因它不起作用?我正在 MAMP 上开发...也许数据库不是为“原子”的东西设置的(今天才在这里听说过!)。
我之前曾尝试使用 foreach 循环遍历 id,然后在 foreach 中执行此操作(编辑:更多代码!)
public function pushing() {
if ($this->request->is('post') || $this->request->is('put')) {
foreach ($this->request->data['User'] as $player => $flag) {
if ($flag) {
$this->User->id = $player; // set ID to player we want to save ($player is id that was suplpied in view to checkbox
$this->User->saveField('data', 'foo'); // then, push the data!
}
}
$this->Session->setFlash(__('Programs were pushed!'));
}
$this->autoRender = false;
$this->redirect(array('action' => 'index'));
}
但这会导致重定向的奇怪结果。无论我在那个动作中将重定向放在哪里,保存只是想做它自己的事情。 $this->autoRender 什么也没做。控制器仍然试图解析到 /push/ 路由
【问题讨论】:
-
它应该可以通过创建
IN()语句来工作。你检查过你的 SQL 日志吗?如果您遇到重定向问题,也可以查看更多代码。 -
两者都应该可以正常工作(第一个更快,因为它只是一个原子查询)。您的问题可能出在其他地方。