Entity add custom properties |
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]
Simple CI 4 project for beginners codeigniter-expenses
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. PHP Code: 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 )
Simple CI 4 project for beginners codeigniter-expenses
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?
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 Thanks, Model::insertBatch() works
Simple CI 4 project for beginners codeigniter-expenses
|
Welcome Guest, Not a member yet? Register Sign In |