Sergioh Lonet
Sergioh Lonet

Reputation: 831

Save data in association table (belonsToMany) Cakephp 3

I have Campaigns and Actions. Each Campaign can has unlimited actions (even can be repeated).

Cakephp documentation say you can save the asociation with actions._ids but I have a problem with this. Each campaign_action has a duration. Then if I use actions._ids I can save the relationship without problems but I can't save duration in each campaign_duration.

Now I am saving data width actions._joinData.action_id and actions._joinData.duration and it works! but the problem is that cakephp creates a new action and save me the relation with the new action created. Example:

I need save in campaign 1 the actions ids 3 and 5 width 25 seconds and 40 seconds respectively.

The insertion in BBDD should be campaign_id 1 - action_id 3 - duration 25 and campaign_id 1 - action_id 5 - duration 40. Now with _joinData, it saves me: new action width id 8(for example) and new action width id 9(for example) and in campaign_actions: campaign_id 1 - action_id 8 - duration 25 and campaign_id 1 - action_id 9 - duration 40

How can I do this?

Would I have to do it manually without cake?

Thanks.

Edit:

This is my data to save (only actions):

 "actions" => array:1 [▼
    0 => array:1 [▼
      "_joinData" => array:3 [▼
        "campaign_action_name" => "A"
        "action_id" => "3"
        "duracion" => "4"
      ]
    ]
  ]

And this is my result entity:

   "actions": array:1 [▼
    0 => Action {#236 ▼
      +"_joinData": CampaignsAction {#266 ▼
        +"campaign_action_name": "A"
        +"action_id": 3
        +"duracion": 4.0
        +"[new]": true
        +"[accessible]": array:6 [▶]
        +"[dirty]": array:3 [▶]
        +"[original]": []
        +"[virtual]": []
        +"[errors]": []
        +"[invalid]": []
        +"[repository]": "CampaignsActions"
      }
      +"[new]": true     // HERE IS THE PROBLEM I THINK
      +"[accessible]": array:21 [▶]
      +"[dirty]": array:1 [▶]
      +"[original]": []
      +"[virtual]": []
      +"[errors]": []
      +"[invalid]": []
      +"[repository]": "Actions"
    }
  ]

Upvotes: 0

Views: 98

Answers (1)

Greg Schmidt
Greg Schmidt

Reputation: 5098

I think your data structure prior to patching should look something like this:

actions => [
    0 => [
        id  => 3,
        _joinData => [
            duration => 40,
        ],
    ],
    1 => [
        id  => 5,
        _joinData => [
            duration => 25,
        ],
    ],
]

Try patching your campaign entity with data like this; if it doesn't work, update the question with the exact data you're patching with and the resulting entity.

Upvotes: 1

Related Questions