私は2つのモデルを持っていますStatement
->hasMany-> LineItem
。
次の配列をのメソッドの$this->saveAll()
1つに渡します。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列は1ずつインクリメントされています。これは、テーブルの現在のauto_incrementと一致するid
という事実にも反映されています。$this->Statement->id
上記のすべてが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')
トランザクションはロールバックされています。
statement_id
では、saveAllを使用しているときに、トランザクションのクエリに追加されないのはなぜですか?