Welcome Guest, Not a member yet? Register   Sign In
[SOLVED] CI4 Entity using datamap to Model-Save
#1

(This post was last modified: 07-16-2021, 03:18 AM by monkenWu.)

Hi, I have some question to the usage of Entity.
For example, I have a entity class `ActivityEntity` as below:

PHP Code:
class ActivityEntity extends Entity
{
    protected $attributes = [
        'key' => null,
        'userKey' => null,
        'name' => null,
        'archivedAt' => null,
        'createdAt' => null,
        'updatedAt' => null,
        'deletedAt' => null,
    ];

    protected $datamap = [
        'user_key' => 'userKey',
        'archived_at' => 'archivedAt',
        'created_at' => 'createdAt',
        'updated_at' => 'updatedAt',
        'deleted_at' => 'deletedAt'
    ];



Since the project obeys the Camel-case, I re-map the column name of the database into Camel-case using `datamap` just like how the documentation describes.
And my `ActivityModel` looks like:

PHP Code:
use App\Entities\ActivityEntity;
class 
ActivityModel extends Model
{
    protected $DBGroup 'default';
    protected $table 'activity';
    protected $primaryKey 'key';
    protected $returnType ActivityEntity::class;
    protected $protectFields true;
    protected $allowedFields = ["user_key""name""archived_at"];

    protected $useSoftDeletes true;
    protected $useTimestamps true;
    protected $dateFormat 'datetime';
    protected $createdField 'created_at';
    protected $updatedField 'updated_at';
    protected $deletedField 'deleted_at';



Encounter problem while building new data using the method below:

PHP Code:
$newActivity = new ActivityEntity();
$newActivity->userKey 1;
$newActivity->name 'activity name';
$activityModel = new ActivityModel();
$activityModel->save($newActivity); 

I was expecting the upper codes will insert a new activity data into the database, however it went wrong. The reason is that when the `save` method processing `ActivityEntity` I passed into, it didn't follow the `datamap` setting to turn `userKey` into `user_key`, hence the database is unable to write normally.

I tried to call the `toArray` method within the Entity and found out the setting of `datamap` really does work, my `userKey` turns into `user_key`, but the auto-transformation I expected did not happen in the Model's `insert` and `save`, which stopped me to deal with `Entity` and create `Activity` through Camel-case.

I'm not sure whether its an error or not, or I misunderstood how to use Entity.
Reply


Messages In This Thread
[SOLVED] CI4 Entity using datamap to Model-Save - by monkenWu - 07-14-2021, 10:32 PM



Theme © iAndrew 2016 - Forum software by © MyBB