Welcome Guest, Not a member yet? Register   Sign In
Entity add custom properties
#1

Hello. I'd like to add a custom property (another object) when requesting find(), findAll() ...
How is this possible within the framework?

If you add public $user - will not be shown in toArray()
The protected $attributes property is not allowed - these are the names of the fields from the table
There is only one way left - to immediately assign $this->user = new User() But I would like to have an initial value as for $attributes = ['user'  => null]
Reply
#2

You can always extend the framework classes (most) and implement whatever logic you need.
To be honest, I don't really understand what the problem is.
Reply
#3

(This post was last modified: 09-05-2022, 10:03 AM by ozornick.)

PHP Code:
 
    
protected $returnType = \App\Models\Entity\Image::class;
    protected 
$afterFind = ['_addExtendProps'];

 
  private function _addExtendProps(Image $image): Image
    
{
        $groups    = \Config\Services::groups();
        $users     = \Config\Services::users();
        // .. code select other Entity
        $image->group  $group;
        $image->user   $user;
        $image->syncOriginal();

        return $image;
    
If you set the $user or $group properties via the magic $this->var - the attribute is available via $image->toArray()

How to initialize an empty attribute $this ->attributes['user'] = null ? To avoid warning.
Use only in the constructor?

And today there was a question with this: $image ->toRawArray()  return virtual $image->user
This breaks $this->builder()->insertBatch($images->toRawArray()); because $image->user doesn't exist in the table (Object of class App\Models\Entity\User could not be converted to string )
Reply
#4

I'll start with the second question.
The Model::insertBatch() method solves your problem. This method will remove fields from the dataset that do not exist in the database table. If you still want to use the QueryBuilder directly, you must clean up the data yourself.

I still don't understand the situation. Excuse me.
When you find an object using the Model::find() method, you add the "user" attribute to the entity.
The only moment when this attribute will not be defined for you is at the moment of creating a new entity.
But it is logical that during creation you will assign the current user to it. So I don’t see the point in the stub (creating an empty user in the constructor), since when exporting (toArray()) it is converted to an empty array.

"To avoid warning." What do you mean?
Reply
#5

That's right
I thought to maintain the integrity of the entity. In some places it may be necessary to have values from $attributes and 'user' will not be in it.
Now, during the discussion, I began to doubt the question  Smile
Thanks, Model::insertBatch() works
Reply




Theme © iAndrew 2016 - Forum software by © MyBB