我有两个模型,Statement
-> hasMany -> LineItem
。
我将以下数组传递给's 方法$this->saveAll()
之一:Statement
$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_incrementid
列增加了 1。这也反映在$this->Statement->id
与表的当前 auto_increment 匹配的事实上。
上述所有情况也适用于该line_items
表,只有 auto_increment 增加了 3。
更新
使用$this->save($data)
时,Statement 被正确保存(当然,没有LineItem
记录)。那么,saveAll 是怎么回事?
更新
所以,我想问题出在我的控制器或模型的某个地方。一些愚蠢的doh!我确定。这是来自我的控制器和模型的代码(为简洁起见,删除了注释和不相关的代码)。
一、型号:
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;
}
}
和控制器:
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');
}
到达某个地方
我在控制器方法中关闭了重定向,并查看了 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')
事务正在回滚。
那么为什么statement_id
在使用 saveAll 时没有将被添加到事务中的查询中呢?