Welcome Guest, Not a member yet? Register   Sign In
How to get data after saving the model
#7

(01-28-2022, 10:53 AM)davis.lasis Wrote:
(01-27-2022, 07:41 AM)Seva Wrote: Created_at, updated_at this is what i want to get.
With the use of entity these fields are - null.

I see only the data that I directly transfer in the array for saving.
Model class automatically sets values for fields created_at, updated_at.

With the use of the entity class, these fields are empty, but maybe I'm doing something wrong.
You should read about entities: https://codeigniter4.github.io/CodeIgnit...ities.html

add new field to database table 'updated_at'

database table users:

id                - integer
username    - string
email          - string
password    - string
updated_at  - datetime
created_at  - datetime

PHP Code:
<?php

namespace App\Models;

use 
CodeIgniter\Model;
use 
App\Entities\UserEntity;

class 
UserModel extends Model
{
    protected $table        'users';
    protected $allowedFields = [
    'username',
    'email',
    'password',
    'updated_at',
    ];
    protected $returnType    UserEntity::class;
    protected $useTimestamps true;


The model uses the users table in the database for all of its activities. We’ve set the $allowedFields property to include all of the fields that we want outside classes to change. The id, created_at, and updated_at fields are handled automatically by the class or the database, so we don’t want to change those. Finally, we’ve set our Entity class as the $returnType. This ensures that all methods on the model that return rows from the database will return instances of our User Entity class instead of an object or array like normal.
PHP Code:
<?php

namespace App\Entities;

use 
CodeIgniter\Entity\Entity;

class 
UserEntity extends Entity
{
    protected $dates = ['created_at''updated_at'];


Read manuals and documentation carefully

I do everything as you wrote, but fields id, created_at, updated_at of entity return is empty when saving the model (insert/update)

PHP Code:
$userModel = new UserModel();
$user = new UserEntity();

$user->fill([
'name' => 'someName',
'email' => 'someEmail',
'password' => 'qwerty'
]);

$userModel->save($user); // insert

echo $user->id// null
echo $user->name// someName
echo $user->email// someEmail
echo $user->password// qwerty
echo $user->created_at// null
echo $user->updated_at// null 
Reply


Messages In This Thread
How to get data after saving the model - by Seva - 01-27-2022, 01:26 AM
RE: How to get data after saving the model - by Seva - 01-28-2022, 10:50 PM



Theme © iAndrew 2016 - Forum software by © MyBB