Yii2: I have a new column and now I get Getting unknown property

407 Views Asked by At

I have a find function in my CarsSearch model:

public function search($params)
{
    $query = Cars::find()->select(['color' => '1']); // This is a longer SQL query.

    $dataProvider = new ActiveDataProvider([
        $query  => $query,
        $this->load($params);
        return $dataProvider;
    ]);
}

I use that $dataProvider in my very simple cars view:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'color'
    ]
]) ?>

But I got this error:

Getting unknown property: app\models\Cars::color

How can I add the color property?

2

There are 2 best solutions below

0
On BEST ANSWER

I see that property color is in your database table cars, so your class Cars must be extended by ActiveRecord. You have to just add color in rules of your model Cars. For example:

['color', 'integer']

The way you added it, the property will be always null except you set some value. If you set it in rules, when you find object, the object will have color with value that is in your database. If you have some questions, give your code from class Cars and CarsSearch

1
On

I added in my cars model as I read and it works:

public $color;