A
A
Artur Kosikov2019-04-08 18:16:55
MySQL
Artur Kosikov, 2019-04-08 18:16:55

How to properly get related data in Yii2?

In B.D. there are tables ` doctors ` and ` clinics `
Simplified: (I write only the fields that are needed for the Subject ...)
Table clinics: id , name (clinics)
Table doctors: id , name (doctors)
Table clinics_doctors: id , clinic_id , doctor_id (link: doctor/clinic)
One doctor can work in several clinics. There are connections. Yii2 Models: Clinics, Doctors, ClinicsDoctors
The task is to get a list of all doctors of a certain clinic...
How I do:

// Получаю массив ID всех врачей клиники (для примера, клиники id = 1)
$doctors_array = ClinicsDoctors::find()->select('doctor_id')->where(['clinic_id' => 1])->column();

// Получаю врачей из таблицы doctors по массиву ID
$doc_clinics = Doctors::find()->where(['IN', 'id', $doctors_array])->all();

It works. But it's embarrassing that there can be several hundred IDs in the array. And if they are doctors of clinics of the whole city...
I think that the solution should be more beautiful. You can also store sets of doctors / clinics
in Redis (this is not so important)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
irishmann, 2019-04-09
@irishmann

Compose and execute a direct query in the database.

B
Boris Korobkov, 2019-04-09
@BorisKorobkov

https://www.yiiframework.com/doc/guide/2.0/en/db-a...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question