Custom attributes in model

How is it possible to define just simple custom attribute? I’ve got the following information:

public function rules()


    return [

        [['ID', 'PinNumber', 'TimeSpent'], 'integer'],

        [['LogTime'], 'safe'],



Now I want to add StartTime (computed, does not exist in the database) attribute that will be calculated based on LogTime and TimeSpent (StartTime = LogTime - TimeSpent).

What should I do to the model and search / filtering etc. in order to get this done properly?

This may be usefull.

"Then you need to compose a query, which calculates volume of the room and performs the sort."

Where and why? Didn’t help that much.

I’d rather take my example and see what places are needed to be touched. Thanks.

Scroll to the top of that page and you will get it.

Now got to the point where the data is in the GridView. How to get the sorting and filtering to work? I need to add the same logic to the SQL query?

All you need is define the attribute in your model class:

class MyModel extends \yii\db\ActiveRecord {

    public $StartTime;


    // (...)


The rest is like with any other attribute (label, rule, search, filtering, …)

I’ve defined this and get the following error when sorting the column:

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘StartTime’ in ‘order clause’

The SQL being executed was: SELECT * FROM logs ORDER BY StartTime LIMIT 20

Error Info: Array


[0] => 42S22

[1] => 1054

[2] => Unknown column 'StartTime' in 'order clause'


This has also an order by example

I’ve already defined the logic in the model how the StarTime is calculated. Do I really need to add that logic also to the query in order to get it working (that’s how I understand the example, but is that correct)? Thx.

Yes, if you want to sort according to that attribute, you have to include it in the query as shown on that page. You don’t have to calculate it elsewhere else, because the value will be returned by the query. If you don’t need sorting, you can leave it out of the query.