K
K
Kir Burov2017-04-09 17:02:04
Yii
Kir Burov, 2017-04-09 17:02:04

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]),
        ]);

One more question: if you need to display several identical tables by category, how to get rid of code repetition in the controller?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2017-04-09
@KirraBu

Good afternoon.
Use relationships for tables.
For example:

public functon getType(){
   return $this->hasOne(Model_name::className(), ['category' => 'type_id'])
}

In the controller ActiveDateProvider() get like this:
$query = Device::find()->with('type')
$device = new ActiveDataProvider([
    'query' => $query
])

In the gridview, you can get the value like this:
[
   'attribute' => 'id'
   'value' => 'type.name'
]

More details here (Working with linked data)

K
Kir Burov, 2017-04-09
@KirraBu

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 question

Ask a Question

731 491 924 answers to any question