# Saving data in multiple tables

**URL:** <https://discourse.cakephp.org/t/saving-data-in-multiple-tables/2541>\
**Category:** Need Help\
**Created:** [May 8, 2017, 5:03pm UTC](https://discourse.cakephp.org/t/saving-data-in-multiple-tables/2541 "2017-05-08T17:03:35Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![DanAlexa](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/danalexa/32/629_2.png) [@DanAlexa](https://discourse.cakephp.org/u/DanAlexa)\
**Post date:** [May 8, 2017, 5:03pm UTC](https://discourse.cakephp.org/t/saving-data-in-multiple-tables/2541/1 "2017-05-08T17:03:35Z")

</div>

Hello,

I know my problem is a question which has been asked already quite often, but the answers given didnt help me, unfortunately.  
Currently I just set up an example database for understanding. I have 2 tables users and phone\_Numbers.  
The UsersModel has a hasMany association with PhoneNumbers and PhoneNumbers a belongsTo association with the UsersModel.  
In my Users\add.ctp I created a form for saving data in both tables and simply added

> \<?= \_\_('Add Phone Number ') ?\> \<?php echo $this-\>Form-\>control('phone\_numbers.number'); echo $this-\>Form-\>control('phone\_numbers.type'); ?\>

In the UsersController I added the association

> $user = $this-\>Users-\>patchEntity($user, $this-\>request-\>getData(), [

> ```
> 'associated' => ['PhoneNumbers']
> ]);
> 
> ```

When typing the data into my form, only the datas for the users table are saved but not the one for phone\_numbers.  
Making use of the debug function I noticed an error in the field user\_id, which is the foreignKey in my phone\_numbers table:

> ‘phone\_numbers’ =\> [  
> (int) 0 =\> object(App\Model\Entity\PhoneNumber) {  
> ‘number’ =\> ‘0123456789’,  
> ‘type’ =\> ‘m’,  
> ‘[new]’ =\> true,  
> ‘[accessible]’ =\> [  
> ‘\*’ =\> true,  
> ‘id’ =\> false  
> ],  
> ‘[dirty]’ =\> [  
> ‘number’ =\> true,  
> ‘type’ =\> true  
> ],  
> ‘[original]’ =\> ,  
> ‘[virtual]’ =\> ,  
> ‘[errors]’ =\> [  
> ‘user\_id’ =\> [  
> ‘\_required’ =\> ‘This field is required’  
> ]  
> ],  
> ‘[invalid]’ =\> ,  
> ‘[repository]’ =\> ‘PhoneNumbers’
> 
> ```
> }
> ],
> 
> ```

so to my understanding the problem seems to be with the foreign key, but I dont understand how to fix it?  
By now this easy thing is giving me a headache, so any advice is welcomed.

P.S.: What are actually the differences between patchEntity() and save() ?

---

<div class="post-metadata">

**Author:** ![DanAlexa](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/danalexa/32/629_2.png) [@DanAlexa](https://discourse.cakephp.org/u/DanAlexa)\
**Post date:** [May 13, 2017, 12:47pm UTC](https://discourse.cakephp.org/t/saving-data-in-multiple-tables/2541/2 "2017-05-13T12:47:53Z")

</div>

any help or a hint is very much appreciated.

---

<div class="post-metadata">

**Author:** ![annabel](https://avatars.discourse-cdn.com/v4/letter/a/ee59a6/32.png) [@annabel](https://discourse.cakephp.org/u/annabel)\
**Post date:** [May 13, 2017, 11:38pm UTC](https://discourse.cakephp.org/t/saving-data-in-multiple-tables/2541/3 "2017-05-13T23:38:54Z")

</div>

You have keyed the inputs for the phone numbers incorrectly.  
See this section in the Cake book for how to create a form that includes hasMany objects: [https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data](https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data)

As your User **hasMany** PhoneNumbers these PhoneNumbers will need to be in an _array_. So your code should look more like:

```
<?php
     echo $this->Form->control('phone_numbers.0.number');
     echo $this->Form->control('phone_numbers.0.type');
?>

```

You could also allow create more inputs so you can add a User with more than one phone number:

```
<?php
     echo $this->Form->control('phone_numbers.0.number');
     echo $this->Form->control('phone_numbers.0.type');
     echo $this->Form->control('phone_numbers.1.number');
     echo $this->Form->control('phone_numbers.1.type');
     echo $this->Form->control('phone_numbers.2.number');
     echo $this->Form->control('phone_numbers.2.type');
?>

```

The difference between `patchEntity()` and `save()` is that you use `patchEntity()` to start building up an entity. This entity will only exist in your computer’s memory until you successfully use `save()` to persist it to the database.

---

<div class="post-metadata">

**Author:** ![DanAlexa](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/danalexa/32/629_2.png) [@DanAlexa](https://discourse.cakephp.org/u/DanAlexa)\
**Post date:** [May 14, 2017, 9:50am UTC](https://discourse.cakephp.org/t/saving-data-in-multiple-tables/2541/4 "2017-05-14T09:50:21Z")

</div>

Hi annabel,

first of all thank u very much for ur reply. I had tried it the way u suggested and as it is also documented in the cookbook. But it doesnt make any difference. Debugging it, the error is still the same:

> [[errors]] =\> Array  
> (  
> [user\_id] =\> Array  
> (  
> [\_required] =\> This field is required  
> )

> ```
> )
> 
> ```

Yesterday, I came across a similar question on github from 2014

> <https://github.com/cakephp/cakephp/issues/5292>
>
> I have this controller and edit action:
> 
> src/Controller/RecordsController
> 
> \`\`\` p…hp
> \<?php
> namespace App\\Controller;
> 
> use App\\Controller\\AppController;
> 
> /\*\*
> \* Edit method
> \*
> \* @param string $id
> \* @return void
> \* @throws \\Cake\\Network\\Exception\\NotFoundException
> \*/
> public function edit($id = null) {
> $record = $this-\>Records-\>get($id, \[
> 'contain' =\> \['Addresses','Businesses.Businesstypes','Organizations','Persons','Telephones.Telephonetypes'\]
> \]);
> if ($this-\>request-\>is(\['patch', 'post', 'put'\])) {
> $record = $this-\>Records-\>patchEntity($record, $this-\>request-\>data,
> \['atomic'=\>false,'associated'=\> \['Addresses','Businesses.Businesstypes','Organizations','Persons','Telephones.Telephonetypes'\]\]
> );
> if ($this-\>Records-\>save($record, \['atomic'=\>false, 'associated'=\> \['Addresses','Businesses.Businesstypes','Organizations','Persons','Telephones.Telephonetypes'\]\])) {
> $this-\>Flash-\>success('The record has been saved.');
> return $this-\>redirect(\['action' =\> 'index'\]);
> } else {
> $this-\>Flash-\>error('The record could not be saved. Please, try again.');
> }
> }
> $telephonetypes = $this-\>Records-\>Telephones-\>Telephonetypes-\>find('list');
> $businesstypes = $this-\>Records-\>Businesses-\>Businesstypes-\>find('list');
> $this-\>set(compact('record', 'users','telephonetypes', 'businesstypes'));
> }
> 
> \`\`\`
> 
> The edit.ctp for the record is:
> 
> \`\`\` php
> \<div class="records form large-10 medium-9 columns"\>
> \<?= $this-\>Form-\>create($record) ?\>
> \<fieldset\>
> \<legend\>\<?= \_\_('Edit Record') ?\>\</legend\>
> \<?php
> echo $this-\>Form-\>input('name');
> echo $this-\>Form-\>input('url');
> echo $this-\>Form-\>input('description');
> echo $this-\>Form-\>input('businesses.0.businesstype\_id', \['options' =\> $businesstypes\]);
> echo $this-\>Form-\>input('telephones.0.telephonetype\_id', \['options' =\> $telephonetypes\]);
> echo $this-\>Form-\>input('telephones.0.telephone');
> echo $this-\>Form-\>input('addresses.0.streetAddress');
> echo $this-\>Form-\>input('addresses.0.addressLocality');
> echo $this-\>Form-\>input('addresses.0.postalCode');
> echo $this-\>Form-\>input('addresses.0.addressCountry');
> echo $this-\>Form-\>input('addresses.0.description',\['label'=\>\_\_('Address Description')\]);
> ?\>
> \</fieldset\>
> \<?= $this-\>Form-\>button(\_\_('Submit')) ?\>
> \<?= $this-\>Form-\>end() ?\>
> \</div\>
> \`\`\`
> 
> When I try to submit form I get this data with debug($record)
> 
> https://gist.github.com/mtkocak/8706aaeb9fb505f3db9f
> 
> \`\`\` php
> var\_dump($this-\>request-\>data):
> 
> array (size=6)
> 'name' =\> string 'Midori Kocak' (length=12)
> 'url' =\> string 'http://www.mtkocak.com' (length=22)
> 'description' =\> string 'My name is Midori!' (length=18)
> 'businesses' =\> 
> array (size=1)
> 0 =\> 
> array (size=1)
> 'businesstype\_id' =\> string '1' (length=1)
> 'telephones' =\> 
> array (size=1)
> 0 =\> 
> array (size=2)
> 'telephonetype\_id' =\> string '1' (length=1)
> 'telephone' =\> string '+420775259871' (length=13)
> 'addresses' =\> 
> array (size=1)
> 0 =\> 
> array (size=5)
> 'streetAddress' =\> string 'Parizska 5' (length=10)
> 'addressLocality' =\> string 'Prague' (length=6)
> 'postalCode' =\> string '110 00' (length=6)
> 'addressCountry' =\> string 'Czech Republic' (length=14)
> 'description' =\> string 'Home Office' (length=11)
> \`\`\`
> 
> If I do validate-\>false in save() method, message says it is updated, if not, I get cannot saved error.

I tried to do it the same way with hidden inputs, but received a saved error. But Im also new to Cakephp and not very much familiar with hidden inputs (just read about it in the documentation), so maybe I handled it the wrong way. Do u know more about hidden inputs?

---

<div class="post-metadata">

**Author:** ![DanAlexa](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/danalexa/32/629_2.png) [@DanAlexa](https://discourse.cakephp.org/u/DanAlexa)\
**Post date:** [May 16, 2017, 10:00am UTC](https://discourse.cakephp.org/t/saving-data-in-multiple-tables/2541/5 "2017-05-16T10:00:40Z")

</div>

solved the problem with hidden inputs. Probably this isnt an elegant way, but at least it works now.

---

<div class="post-metadata">

**Author:** ![alejduin](https://avatars.discourse-cdn.com/v4/letter/a/5f9b8f/32.png) [@alejduin](https://discourse.cakephp.org/u/alejduin)\
**Post date:** [August 27, 2017, 7:33pm UTC](https://discourse.cakephp.org/t/saving-data-in-multiple-tables/2541/6 "2017-08-27T19:33:05Z")

</div>

Hello, could you please explainme how did you solve this issue, I’m truing to do that so…

---

<div class="post-metadata">

**Author:** ![donnidani](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/donnidani/32/744_2.png) [@donnidani](https://discourse.cakephp.org/u/donnidani)\
**Post date:** [August 28, 2017, 8:22am UTC](https://discourse.cakephp.org/t/saving-data-in-multiple-tables/2541/7 "2017-08-28T08:22:27Z")

</div>

> [@DanAlexa](#):
>
> PhoneNumbers

if u trying to save for new record(s) u can follow to what annabel sugested,

but if u trying to update/edit record(s) along with associated data.

since the id field is protected by default inside the entity rule, (u can check the related model entity)  
so you need to make the ids of associated data accessible.

example :

$this-\>Users-\>patchEntity($entity, $this-\>request-\>getData, [  
‘associated’ =\> [  
‘UserProfiles’ =\> [‘accessibleFields’ =\> [‘id’ =\> true]  
]  
]  
]);

by this you don’t need hidden field for defining the IDs.

sorry for my bad english, hope this might help.

---

<div class="post-metadata">

**Author:** ![pjp.comp](https://avatars.discourse-cdn.com/v4/letter/p/848f3c/32.png) [@pjp.comp](https://discourse.cakephp.org/u/pjp.comp)\
**Post date:** [March 15, 2019, 8:49am UTC](https://discourse.cakephp.org/t/saving-data-in-multiple-tables/2541/9 "2019-03-15T08:49:19Z")

</div>

I think this link can be helpful for cakephp3. you can crud accordingly.

[[creating-inputs-for-associated-data]](https://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-data)

---

<div class="post-metadata">

**Author:** ![wakikuk](https://avatars.discourse-cdn.com/v4/letter/w/e95f7d/32.png) [@wakikuk](https://discourse.cakephp.org/u/wakikuk)\
**Post date:** [May 14, 2019, 12:37am UTC](https://discourse.cakephp.org/t/saving-data-in-multiple-tables/2541/10 "2019-05-14T00:37:33Z")

</div>

Use Entities and save with foreach…
