C
C
Cyril2017-08-12 21:28:48
MySQL
Cyril, 2017-08-12 21:28:48

How to properly use CASE WHEN in ActiveRecord in YII2?

The YII2 application has an ActiveRecord model , SomeModel , which describes the table some_table . How can I make sure that I can specify the CASE WHEN SQL construct in the select method ?
When I write this:

$data = SomeModel::find()
    ->select([
        'some_table.region_id',
        'CASE WHEN some_table.region_id IN (1,2,3,4) THEN true ELSE false END AS region_in_range'
    ])
    ->where([
        'some_table.id' => $id,
    ])
    ->all()

and I'm trying to get the value of the region_in_range field in a loop:
foreach($data as $item) {
    echo $item->region_in_range;
}

then YII writes an error Getting unknown property region_in_range .
The SomeModel model has a standard form:
class SomeModel extends ActiveRecord {
    public static function tableName() {
        return 'same_table';
    }
}

How to make region_in_range field known to YII? And in general, is it possible in principle to prescribe CASE WHEN using ActiveRecord? Maybe I put CASE WHEN in the wrong place at all?
Help me figure out how to combine CASE WHEN and ActiveRecord. Or it can be reached only means Query?
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
matperez, 2017-08-12
@belyaevcyrill

Add a public region_in_range field to the model, after which the ORM will fill it with data, and you can access it.

M
Maxim Timofeev, 2017-08-12
@webinar

since you don’t need an object, you can add ->asArray()or do without AR altogether.
But if we already use an object, then it’s probably worth not choosing from the base, but making a method in the model and returning true or flse

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question