A
A
AlikDex2015-08-01 18:43:47
Yii
AlikDex, 2015-08-01 18:43:47

Yii2, Can I add my own property to an ActiveRecord object?

More precisely, not to the object itself, but to the attributes of the collection of this object. Those. along the way, I calculate additional parameters from the record from the database, and I would like to add them to AR, so that later I can display them through standard widgets, with sorting. I hope I explained clearly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Pavlenko, 2015-08-02
@AlikDex

Clearly explained.
Just add your properties inside the class.
For example

<?php
//Не забудьте о неймспейсах
//...
class User extends ActiveRecord
{
public $test;
//остальной код...
}

This way you will be able to write and take data from test. By the way, you can also write "test" later in the validators, in attributeLabels, and so on.
The only difference is that they will not be saved to the database (since there is nowhere), and after validation or saving, you need to think about this data yourself.
You can generate the field automatically by overriding the afterFind() method (read the documentation). There may be subtleties about sorting, but as far as I understand, everything should be pretty good, though you will have to extend the sort class and specify its behavior when using this property. To do this, read the documentation on the sort object \yii\data\Sort

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question