Welcome Guest, Not a member yet? Register   Sign In
How use ModelObject->save($entityObject) well?
#1

(This post was last modified: 07-19-2022, 04:24 AM by cwwjsyc.)

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)); 
Reply
#2

How about this?

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

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

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;
    
Reply
#5

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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB