Save manytomany with additional field

Simplified i have 3 Tables:

  • dishes (id, name, created, modified)
  • dishsizes (id, name, created, modified)
  • dishes_dishsizes (id, dish_id, dishsize_id, unitprice)

Table dishsizes is filled with values.

What i want to do is to add a new dish and define in which dishsizes one can order the dish and what the unitprice per dishsize is.

In my Form “add” i tried the following:

            foreach($dishsizes AS $dishsize) {
          echo $this->Form->control('dishsizes['.$dishsize->id.'].unitprice', ['label'=>$dishsize->name,'type'=>'number','min'=>1, 'step'=>'any']);

But it seems not to be the right way.
By doing so, after patching in the controller it tries to create new dishsizes.

Can anyone help me?

Best regards

Do you have existing records in the database for this? If so, read one of those dish records with dishsizes contained, a dump that entity. The naming scheme in your view should match the way that the data exists in the entity you’re trying to patch it into.

Thank you very much.
you helped me on the way.

my working solution:

foreach($dishsizes AS $dishsize) {
     echo $this->Form->hidden('dishsizes.'.$i.'.id', ['value' => $dishsize->id]);
     echo $this->Form->control('dishsizes.'.$i.'._joinData.unitprice',['label'=>__('Unitprice for '.$dishsize->name)]);

btw, do you know a better approach for the loop ($i=0,…$i++)

foreach ($dishsizes as $i => $dishsize) ?

Thanks again for your help.
As you can see, i´m not really good in PHP :frowning:

PHP double quote magic:
echo $this->Form->hidden("dishsizes.$");

1 Like