Answer the question
In order to leave comments, you need to log in
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()
foreach($data as $item) {
echo $item->region_in_range;
}
class SomeModel extends ActiveRecord {
public static function tableName() {
return 'same_table';
}
}
Answer the question
In order to leave comments, you need to log in
Add a public region_in_range field to the model, after which the ORM will fill it with data, and you can access it.
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 questionAsk a Question
731 491 924 answers to any question