Alex Malev
Alex Malev

Reputation: 177

Relations and Active Query in Yii2?

I have 2 tables:

Auto

id (pk) int

name varchar100

color int

AutoComparison

auto1_id

auto2_id

status

Where:

(*status - 
id 0 new

id 1 old

id 2 broken)

I need to select all cars whose status (id 2 "broken") and count the number of them.

The question that I need to change in the model and insert into the view file, in order to display the number of broken auto's. (Framework Yii2)

Upvotes: 2

Views: 6872

Answers (1)

deacs
deacs

Reputation: 4309

You can access your relations by calling the relation as you would a property of the model.

To count:

$count = AutoComparison::find()->where('status = 2')->count();

To select the models:

$models = AutoComparison::find()->where('status = 2')->all();

Show the names and colors of the broken cars:

foreach ($models as $model) {
    echo 'Car name: ' . $model->auto->name;
    echo '<br/>';
    echo 'Car color: ' . $model->auto->color;
}

Upvotes: 4

Related Questions