CodeIgniter Forums
How use ModelObject->save($entityObject) well? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: How use ModelObject->save($entityObject) well? (/showthread.php?tid=82521)



How use ModelObject->save($entityObject) well? - cwwjsyc - 07-19-2022

Model has a snowflakeId as primaryKey.  
in ver 4.2.1  can not allow primaryKey in $allowedFields array.

How can use Entity and Model correctly ?

PHP Code:
$userArray = [
    'key' => snowFlakeId(), //primaryKey
    'userName' => 'XXXX',
];

$this->userModel->save(new \App\Entities\UserEntity($userArray)); 



RE: How use ModelObject->save($entityObject) well? - kenjis - 07-24-2022

How about this?

PHP Code:
$this->userModel->insert(new \App\Entities\UserEntity($userArray)); 



RE: How use ModelObject->save($entityObject) well? - cwwjsyc - 07-26-2022

CodeIgniter\Database\Exceptions\DataException
There is no primary key defined when trying to make insert.
It can not work. must put primaryKey in $allowedFields.


RE: How use ModelObject->save($entityObject) well? - cwwjsyc - 07-26-2022

In BaseModel ,This function is not a good idea. for resolved insert and update. 
PHP Code:
protected function doProtectFields(array $data): array
    {
        if (! $this->protectFields) {
            return $data;
        }

        if (empty($this->allowedFields)) {
            throw DataException::forInvalidAllowedFields(static::class);
        }

        foreach (array_keys($data) as $key) {
            if (! in_array($key$this->allowedFieldstrue)) {
                unset($data[$key]);
            }
        }

        return $data;
    



RE: How use ModelObject->save($entityObject) well? - kilishan - 07-26-2022

The $allowedFields property is there to protect against mass assignment attacks. Allowing a primary key in there would, in careless code, allow a user to submit an id with a form and have the id updated. Something that definitely needs to be guarded against. AllowedFields does not stop you from assigning that value individually, though, so you could do something like:

PHP Code:
$userArray = [
    
'key' => snowFlakeId(), //primaryKey
    
'userName' => 'XXXX',
];
$user = new UserEntity($userArray);
$user->key snowFlakeId();
$this->userModel->save($user); 

Another option is to not have the snowflake ID as the primary key. Keep an autoincrementing id as the primary, and then have a snowflake column, or something with the id. Put an index on that column and then do your finds by that column instead of the primary key. This would simplify your code a little since you wouldn't have to work around the mass assignment issue.