DS87
DS87

Reputation: 602

Cakephp 3 store associated data

I switched from cakephp2 to cakephp3. Here I cannot understand, how associated data can be stored. I have a table called Orders and a table called Ordersarticles. There is a view where the order information and multiple orderarticles are putted in. Now I want do store the data in the controller.

I have the following code

  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.'));
  }

The orderArticles in the loop are prepared for the right format. However, when I want to store the information, only the order, not the orderarticles are stored. I have absolutely no idea how I also can store the additional information...

I also tried to 1st store the order, get the inserted id and then store the orderarticles. But I totally failed. I feel like beeing new in Cakephp. Can you help me?

Upvotes: 0

Views: 42

Answers (1)

CodeWhisperer
CodeWhisperer

Reputation: 1195

I guess you wan't to do something like this after you've saved the order.

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

Upvotes: 1

Related Questions