我从cakephp2切换到cakephp3。在这里我无法理解,如何存储相关数据。我有一个名为Orders的表和一个名为Ordersarticles的表。有一个视图,其中订购了订单信息和多个orderarticle。现在我想将数据存储在控制器中。
我有以下代码
public function add(){
$order = $this->Orders->newEntity();
if ($this->request->is('post')) {
$order = $this->Orders->patchEntity($order, $this->request->getData());
$i = 0; //Index for each Field
foreach($order->Orderarticles['article_id'] as $oaarticleid){
$orderarticles = [
'article_id' => $oaarticleid,
'amount' => $order->Orderarticles['amount'][$i]
];
$i++;
}
$order['Orderarticles'] = $orderarticles;
//Store Order
if ($result = $this->Orders->save($order)) {
//Store orderArticles
$this->Flash->success(__('The order has been saved.'));
//return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The order could not be saved. Please, try again.'));
}
循环中的orderArticles准备正确的格式。但是,当我想存储信息时,只存储订单,而不是存储订单。我完全不知道如何存储其他信息...
我还尝试先存储订单,获取插入的ID,然后存储orderarticles。但我完全失败了。我觉得在Cakephp中有新的东西。你能救我吗?
答案 0 :(得分:1)
我猜你在保存订单后不想这样做。
if ($result = $this->Orders->save($order)) {
$articles = $this->request->getData("articles");
$i = 0;
foreach ($articles as $article) {
$data = [
'article_id' => $result->id,
'amount' => $i++
];
$article = $this->Orderarticles->newEntity();
$article = $this->Orderarticles->patchEntity($article, $data);
$this->Orderarticles->save($article);
}
}