我有两个模型,Statement
-> hasMany-> LineItem
。
我将以下数组传递给$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_increment id
列已增加1。这也反映在$this->Statement->id
与表的当前auto_increment匹配的事实上。以上所有内容对于
line_items
表同样适用,只有auto_increment增加了3。更新资料
使用
$this->save($data)
时,正确保存了该语句(当然,没有LineItem
记录)。那么,saveAll怎么了?更新资料
因此,我想问题出在我的控制器或模型中。笨蛋我确定。这是我的控制器和模型中的代码(为简洁起见,删除了注释和无关的代码)。
一,模型:
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')
事务正在回滚。
那么,为什么在使用saveAll时不将
statement_id
添加到事务中的查询中? 最佳答案
默认情况下,Cake期望line_items上的外键为statement_id。您尚未显示表结构。实际上在line_items上有一列statement_id吗?
关于php - CakePHP离奇的saveAll问题。返回true,但数据库中不返回任何内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4079877/