我有两个模型,Statement
-> hasMany -> LineItem
。
我将以下数组传递给 Statement
方法之一内的 $this->saveAll()
:
$data = array(
'Statement' => array(
'employee_id' => 1
),
'LineItem' => array(
0 => array('job_id' => 1),
1 => array('job_id' => 9),
2 => array('job_id' => 12),
)
);
$this->saveAll($data) == true
,但是当我检查数据库中的statements
表时,它是空的。奇怪的一点是什么? auto_increment id
列已增加 1。$this->Statement->id
与表的当前 auto_increment 匹配这一事实也反射(reflect)了这一点。
以上所有内容也适用于 line_items
表,只是 auto_increment 增加了 3。
更新
当使用$this->save($data)
时,Statement被正确保存(当然,没有LineItem
记录)。那么,saveAll 是怎么回事?
更新
所以,我认为问题出在我的 Controller 或模型中的某个地方。我确信这是一些愚蠢的时刻。这是我的 Controller 和模型中的代码(为简洁起见,删除了注释和不相关的代码)。
一、型号:
class Statement extends AppModel {
public $belongsTo = array('CompanyStatement', 'Employee');
public $hasMany = array('LineItem');
public $name = 'Statement';
public function build_statement($data = NULL) {
if (!empty($data)) {
if ($this->saveAll($data)) {
$result = array(
'message' => 'Statement was saved.',
'element' => 'flash_success',
'success' => TRUE
);
} else {
$result = array(
'message' => 'There was a problem saving.',
'element' => 'flash_error',
'success' => FALSE
);
}
} else {
$result = array(
'message' => 'No data was received.',
'element' => 'flash_error',
'success' => FALSE
);
}
return $result;
}
}
Controller :
class StatementsController extends AppController {
public $name = 'Statements';
public function create_new_statement() {
$result = $this->Statement->build_statement($this->data);
$this->Session->setFlash($result['message'], $result['element']);
$this->redirect(array(
'controller' => 'statements',
'action' => 'edit',
$this->Statement->id
));
}
public function edit($id = NULL) {
$this->set('statement' => $this->Statement->findById($id));
}
}
LineItem 模型非常简洁:
class LineItem extends AppModel {
public $name = 'LineItem';
public $belongsTo = array('Statement', 'Job');
}
到达某个地方
我在 Controller 方法中关闭了重定向,并查看了 SQL 转储:
Warning (512): SQL Error: 1452: Cannot add or update a child row:
a foreign key constraint fails (`database`.`line_items`,
CONSTRAINT `line_items_ibfk_1`
FOREIGN KEY (`statement_id`) REFERENCES `statements` (`id`)
ON DELETE CASCADE ON UPDATE NO ACTION)
[CORE\cake\libs\model\datasources\dbo_source.php, line 681]
Query: INSERT INTO `line_items` (`job_id`, `modified`, `created`) VALUES (1, '2010-11-02 15:22:39', '2010-11-02 15:22:39')
Query: INSERT INTO `line_items` (`job_id`, `modified`, `created`) VALUES (9, '2010-11-02 15:22:39', '2010-11-02 15:22:39')
Query: INSERT INTO `line_items` (`job_id`, `modified`, `created`) VALUES (10, '2010-11-02 15:22:39', '2010-11-02 15:22:39')
事务正在回滚。
那么,为什么在使用 saveAll 时没有将 statement_id
添加到事务中的查询中?
最佳答案
当我忘记提交事务时,这种情况偶尔会发生在我身上。您是否禁用了自动提交?您使用交易吗?您是否忘记提交或告诉 cakePHP 您需要提交?
关于php - CakePHP 奇怪的 saveAll 问题。返回true,但数据库中没有任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4079877/