patchEntity dont save data into newly created field


#1

Hi,

I am using cakephp 3.3.15. I have a category table in which later on, as per need, I created an additional field ‘user_id’ to know which category is created by which user. A user can update his business data and can create the category on the fly if he needs to, like the business started serving in a new category.

My code like this

$serviceCategory = TableRegistry::get('ServiceCategory');
$new_service_category = $serviceCategory->newEntity();
$this->request->data['name'] = 'abc';
$this->request->data['sub_id'] = 12;//parent_cat
$this->request->data['user_id'] = 28;//
$new_service_data = $serviceCategory->patchEntity($new_service_category, $this->request->data);
$save_data = $serviceCategory->save($new_service_data);

\Model\Table\ServiceCategoryTable.php
have these fundtions

public function initialize(array $config){
parent::initialize($config);
$this->table(DB_PREFIX.‘service_categories’);
$this->displayField(‘id’);
$this->primaryKey(‘id’);
}

public function validationDefault(Validator $validator){
$validator
->notEmpty(‘user_id’, ‘Select a user.’);

    $validator
        ->notEmpty('name', 'Category Name is required field.');
    
    return $validator;
}

I dont have any entity file in “\Model\Entity”. I also read about “accessible” and “accessibleFields” fields but don’t know how to use them and make “user_id” field accessible at run time?

Right now the inser query get generated like

INSERT INTO hh_service_categories (sub_id, name) VALUES (12, ‘abc’);

which must be like

INSERT INTO hh_service_categories (sub_id, name, user_id) VALUES (12, ‘abc’, ‘28’);

Please help.


#2

Guessing that your ORM cache is still reflecting the old schema. bin/cake orm_cache clear should do the trick, or else manually remove the relevant file(s) from tmp/cache/models.


#3

Hi Zuluru,

Thanks for your reply.

If I manually remove the concerned file from “/tmp/cache/models” which is like “myapp_cake_model_default_<TABLE_NAME>” and just refresh any page of my site, will it through any fatal error?

Thanks,


#4

No, any file under /tmp can safely be removed at any time. If the cache isn’t there, it’ll regenerate it through database introspection.


#5

This is ugly.
use

$this->request->withData()

#6

Or, even simpler,

$save_data = $serviceCategory->save($serviceCategory->newEntity([
    'name' => 'abc',
    'sub_id' => 12,
    'user_id' => 28,
]));

and skip all the intermediate stuff.