# Cake "ignores" inserting associated data

**URL:** <https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752>\
**Category:** Need Help\
**Created:** [March 7, 2019, 10:51am UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752 "2019-03-07T10:51:09Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![FinlayDaG33k](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/finlaydag33k/32/1049_2.png) [@FinlayDaG33k](https://discourse.cakephp.org/u/FinlayDaG33k)\
**Post date:** [March 7, 2019, 10:51am UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/1 "2019-03-07T10:51:09Z")

</div>

I found an issue in my application where when a user registers, it doesn’t insert the `firstname` and `lastname` into the associated table.  
This was “intended” behaviour (more like: I forgot to implement this) back then so I started to fix it.

Fast forward two days and I can’t get it to work.  
This is what I want:

1. Create a new user entity (for the username, email, password and creation date) for the `Users` (named `users` in the db) table
2. Add data to the associated `UsersDetails` (named `users_details` in the db) table
3. Save it all
4. Check whether it went right (to show success message or error message as needed)

This is the code I have currently written for that:

```auto
$user = $this->Users->newEntity([
  'username' => $this->request->getData('username'),
  'email' => $this->request->getData('email'),
  'password' => $this->request->getData('password'),
  'created' => date("Y-m-d H:i:s"),
  'users_details' => [
    'firstname' => '',
    'lastname' => ''
  ]
]);

if($this->Users->save($user)) {
...

```

The user is inserted into the `Users` table but Cake seems to “ignore” the fact that I added stuff to the `UsersDetails` table as well (so it doesn’t add a new entry to it).

This us my `User` entity file:

```auto
class User extends Entity {
    use UserTrait;

    protected $_accessible = [
        'username' => true,
        'email' => true,
        'password' => true,
        'created' => true,
        'articles' => true,
        'roles' => true,
        'users_details' => true
    ];

    protected $_hidden = [
        'password'
    ];
}

```

The `UsersTable` has an association to the `UsersDetails` table:

```auto
$this->hasOne('UsersDetails', [
    'foreignKey' => 'id',
    'joinType' => 'INNER'
]);

```

How can I make it work?

UPDATE: changed the `belongsTo` to `hasOne`

---

<div class="post-metadata">

**Author:** ![Graziel](https://avatars.discourse-cdn.com/v4/letter/g/71c47a/32.png) [@Graziel](https://discourse.cakephp.org/u/Graziel)\
**Post date:** [March 7, 2019, 11:29am UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/2 "2019-03-07T11:29:21Z")

</div>

rename `users_details` to `users_detail` as its `belongsTo`

[https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongsto-associations](https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongsto-associations)

> When saving belongsTo associations, the ORM expects a single nested entity named with the **singular**

when in doubt how your post structure should looks like you can always get record first and take a peek

```auto
$user = $this->Users->findById(1)->contain(['UsersDetails'])->first();
dd($user);

```

---

<div class="post-metadata">

**Author:** ![FinlayDaG33k](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/finlaydag33k/32/1049_2.png) [@FinlayDaG33k](https://discourse.cakephp.org/u/FinlayDaG33k)\
**Post date:** [March 7, 2019, 11:37am UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/3 "2019-03-07T11:37:22Z")

</div>

> [@Graziel](#):
>
> $user = $this-\>Users-\>findById(1)-\>contain([‘UsersDetails’])-\>first();  
> dd($user);

Doing this results in the error:

> The UsersDetails association is not defined on Users.

Last time I [encountered](https://discourse.cakephp.org/t/the-usersdetails-association-is-not-defined-on-users/5604) this issue I forgot to load the model (which I did this time).

---

<div class="post-metadata">

**Author:** ![Graziel](https://avatars.discourse-cdn.com/v4/letter/g/71c47a/32.png) [@Graziel](https://discourse.cakephp.org/u/Graziel)\
**Post date:** [March 7, 2019, 11:40am UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/4 "2019-03-07T11:40:46Z")

</div>

sounds like wrong namespace / filename / letter casing

---

<div class="post-metadata">

**Author:** ![FinlayDaG33k](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/finlaydag33k/32/1049_2.png) [@FinlayDaG33k](https://discourse.cakephp.org/u/FinlayDaG33k)\
**Post date:** [March 7, 2019, 11:50am UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/5 "2019-03-07T11:50:53Z")

</div>

```auto
<?php
namespace Kikioboeru\Kikioboeru\Model\Table;

class UsersDetailsTable extends Table {
...

```

Loaded in the controller with:

```auto
$this->loadModel('Kikioboeru/Kikioboeru.UsersDetails');

```

---

<div class="post-metadata">

**Author:** ![Graziel](https://avatars.discourse-cdn.com/v4/letter/g/71c47a/32.png) [@Graziel](https://discourse.cakephp.org/u/Graziel)\
**Post date:** [March 7, 2019, 12:03pm UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/6 "2019-03-07T12:03:27Z")

</div>

you are loading `UsersDetails` and trying to use `Users` table?

---

<div class="post-metadata">

**Author:** ![FinlayDaG33k](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/finlaydag33k/32/1049_2.png) [@FinlayDaG33k](https://discourse.cakephp.org/u/FinlayDaG33k)\
**Post date:** [March 7, 2019, 12:07pm UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/7 "2019-03-07T12:07:54Z")

</div>

I also have the `Users` Table loaded.  
Like I said in the OP, I want to create a new `user` entity for the `username`, `password` and `email` and have associated data inserted into the `UsersDetails` table (the `firstname` and `lastname` of the user)

---

<div class="post-metadata">

**Author:** ![FinlayDaG33k](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/finlaydag33k/32/1049_2.png) [@FinlayDaG33k](https://discourse.cakephp.org/u/FinlayDaG33k)\
**Post date:** [March 7, 2019, 1:30pm UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/8 "2019-03-07T13:30:01Z")

</div>

So I have some progress.  
`$this->Users` has **no** associations at all (even though specified in the `UsersTable`).

```auto
dd($this->Users);

```

results in:

```auto
Table {#239 
  +"registryAlias": "Users"
  +"table": "users"
  +"alias": "Users"
  +"entityClass": "Cake\ORM\Entity"
  +"associations": []
  +"behaviors": []
  +"defaultConnection": "default"
  +"connectionName": "default"
}

```

however, `TableRegistry::get('Kikioboeru/Kikioboeru.Users')` does have associations:

```auto
$usersTable = TableRegistry::get('Kikioboeru/Kikioboeru.Users');
dd($usersTable);

```

results in:

```auto
UsersTable {#272 
  +"registryAlias": "Kikioboeru/Kikioboeru.Users"
  +"table": "users"
  +"alias": "Users"
  +"entityClass": "Kikioboeru\Kikioboeru\Model\Entity\User"
  +"associations": array:3 [
    0 => "articles"
    1 => "roles"
    2 => "usersdetails"
  ]
  +"behaviors": array:1 [
    0 => "Timestamp"
  ]
  +"defaultConnection": "default"
  +"connectionName": "default"
}

```

Is this a bug in CakePHP or?

For those wondering, this is my `initialize` method:

```auto
public function initialize() {
      parent::initialize();

      $this->loadModel('Kikioboeru/Kikioboeru.Users');
      $this->loadModel('Kikioboeru/Kikioboeru.UsersDetails');
      $this->loadModel('Kikioboeru/Kikioboeru.ResetTokens');
      $this->loadModel('Kikioboeru/Kikioboeru.AuthTokens');
}

```

---

<div class="post-metadata">

**Author:** ![FinlayDaG33k](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/finlaydag33k/32/1049_2.png) [@FinlayDaG33k](https://discourse.cakephp.org/u/FinlayDaG33k)\
**Post date:** [March 7, 2019, 1:36pm UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/9 "2019-03-07T13:36:26Z")

</div>

Using the TableRegistry (instead of `$this->Users`) as shown above does make the issue go away.  
Could somebody explain me why, even though I loaded the model it uses a completely different model instead?  
It seems to have used some build-in model(?) instead of the one I specified in my controller.

---

<div class="post-metadata">

**Author:** ![Graziel](https://avatars.discourse-cdn.com/v4/letter/g/71c47a/32.png) [@Graziel](https://discourse.cakephp.org/u/Graziel)\
**Post date:** [March 7, 2019, 3:16pm UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/10 "2019-03-07T15:16:31Z")

</div>

whats in `parent::initialize()` ? maybe you already have loaded `Users` table before loading your plugin `Users` table version

---

<div class="post-metadata">

**Author:** ![raul338](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/raul338/32/69_2.png) [@raul338](https://discourse.cakephp.org/u/raul338)\
**Post date:** [March 7, 2019, 3:49pm UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/11 "2019-03-07T15:49:42Z")

</div>

Can you can use setProperty (or propertyName in array) to the relation to try force the association to be saved?

---

<div class="post-metadata">

**Author:** ![MarceliSzpak](https://avatars.discourse-cdn.com/v4/letter/m/4af34b/32.png) [@MarceliSzpak](https://discourse.cakephp.org/u/MarceliSzpak)\
**Post date:** [March 7, 2019, 5:51pm UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/12 "2019-03-07T17:51:40Z")

</div>

How about

```
$userData =[
    'username' => $this->request->getData('username'),
    'email' => $this->request->getData('email'),
    'password' => $this->request->getData('password'),
    'created' => date("Y-m-d H:i:s"),
    'users_details' => [
        'firstname' => '',
        'lastname' => ''
    ]
];

```

$user = $this-\>Users-\>newEntity($userData, [‘associated’ =\> ‘UserDetails’]);  
pr($user);

---

<div class="post-metadata">

**Author:** ![FinlayDaG33k](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/finlaydag33k/32/1049_2.png) [@FinlayDaG33k](https://discourse.cakephp.org/u/FinlayDaG33k)\
**Post date:** [March 7, 2019, 7:43pm UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/13 "2019-03-07T19:43:26Z")

</div>

> [@Graziel](#):
>
> whats in `parent::initialize()` ?

There is one note of `$this->loadModel('Users');` in the plugin’s AppController!  
Unfortunately, I’ll have to try this out tomorrow when I have access to my workstation again.  
Will report back!

---

<div class="post-metadata">

**Author:** ![FinlayDaG33k](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/finlaydag33k/32/1049_2.png) [@FinlayDaG33k](https://discourse.cakephp.org/u/FinlayDaG33k)\
**Post date:** [March 8, 2019, 9:04am UTC](https://discourse.cakephp.org/t/cake-ignores-inserting-associated-data/5752/14 "2019-03-08T09:04:16Z")

</div>

Jepp, this seemed to be the issue…

I have updated the “rules” of the project to prevent these issues down the road.
