Answer the question
In order to leave comments, you need to log in
How to correctly build a query in ActiveDataProvider?
I am new to PHP and Yii2 so I have a lot of questions.
There are two tables
device [id, type_id, name]
device_type [id, type_name, category]
linked by the type_id field
How to correctly select all device records whose device_type.category is equal to a certain value, so that they can then be displayed in GridView ?
After searching and thinking, I got this in the controller
$device = new ActiveDataProvider([
'query' => Device::find()
->from('device')
->leftJoin('device_type', 'device_type.id=device.type_id')
->where(['device_type.category' => 3]),
]);
Answer the question
In order to leave comments, you need to log in
Good afternoon.
Use relationships for tables.
For example:
public functon getType(){
return $this->hasOne(Model_name::className(), ['category' => 'type_id'])
}
$query = Device::find()->with('type')
$device = new ActiveDataProvider([
'query' => $query
])
[
'attribute' => 'id'
'value' => 'type.name'
]
slo_nik Thanks for the answer.
Found the answer from your link.
Maybe someone will come in handy.
To access the fields of a related table in an ActiveDateProvider() query
$device = new ActiveDataProvider([
'query' => Device::find()
->joinWith('type')
->where(['device_type.category'=>2]),
]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question