2017-08-07 61 views
0

我從cakephp2切換到cakephp3。在這裏我無法理解,關聯數據如何存儲。我有一個名爲Orders的表和一個名爲Ordersarticles的表。有一個視圖,訂單信息和多個結構被放入。現在我想要將數據存儲在控制器中。Cakephp 3存儲相關數據

我有以下代碼

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

您可以使用如下命令中的id:'$ orderId = $ result-> id'這將返回已保存訂單的ID。現在你可以使用'$ orderId'在orderaticles表中添加一個外鍵。 – CodeWhisperer

+0

我知道這件事。但是,我如何才能存儲訂單條款?這是我的問題! – DS87

回答

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); 
     } 
    } 
+0

你是我本週的個人英雄(雖然它只是星期一:-))。最後,我必須去'$ this-> Orders-> Orderarticles-> newEntity()'。我不完全理解閱讀文檔的patchEnitity。第一個參數是什麼?是否應該修補類似於對象的類型? – DS87

+0

patchEntity中的第一個參數用於定義您可以保存的極其數據。它就像一個包含數據庫表所有可能列的框架。 – CodeWhisperer