PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, January 10, 2022

[FIXED] Cakephp 3.0 Save associated model

 January 10, 2022     associated-object, cakephp, cakephp-3.0, model-associations, save     No comments   

Issue

I am learning cakePHP 3.0 and have some problem with saving associated data on my model.

I try to save a Client with associated data of ClientPreferences

ClientTable

class ClientsTable extends Table
{
    public function initialize(array $config)
    {
        (...)
        $this->belongsTo('ClientPreferences', [
            'foreignKey' => 'client_preferences_id'
        ]);
    }
}

ClientController

$aClient = $this->Clients->newEntity();
$aClient = $this->Clients->patchEntity($aClient, $this->request->data);

$aClientPreference = $this->Clients->ClientPreferences->newEntity();
$aClientPreference->my_field = 'my value';

$aClient->ClientPreferences = $aClientPreference;

$this->Clients->save($aClient, ['associated' => ['ClientPreferences']];

The Client entity is correctly saved, but not the associated ClientPreferences entity and there is no error thrown by Cake.

I have tried to follow this : http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-with-associations

But haven't find any issue to do it properly. Do anybody have an advice ?

Thank you in advance.


Solution

Conventions, conventions, conventions

There's clearly a difference in the examples that you've linked, take a closer look at the property names, and if you scroll down a little further, you'll find an explanation specifically for belogsTo associations.

When saving belongsTo associations, the ORM expects a single nested entity at the singular, underscored version of the association name. For example: [...]

Cookbook > Saving Data > Saving BelongsTo Associations

So for belongsTo associations, the property name is by default expected to be lowercased and underscored, ie $aClient->client_preference.

Your foreign key should btw. be singular too in order to match the conventions, ie client_preference_id, even though it's just the property name causing the problem.

See also Cookbook > Associations > BelongsTo Associations (especially the foreignKey and propertyName options)



Answered By - ndm
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing