R
R
Ruslan Kasymov2015-04-20 16:19:53
Yii
Ruslan Kasymov, 2015-04-20 16:19:53

How to select data in YII2 taking into account the value in the link table?

There is a Personal model and there is a Clinic model.
The relationship between them is many-to-many through the linking table l_personal2clinic.
In the Personal model, the relationship is described as follows:

public function getClinics() {
        return $this->hasMany(Clinic::className(), ['id' => 'clinic_id'])
          ->viaTable('l_personal2clinic', ['personal_id' => 'id'])
          ->andWhere(['status' => 1]);
    }

How to select from the Personal model all those who are associated with one specific clinic, say with clinic_id = 5
Or better yet, not by one clinic ID, but by several at once ... If possible.
In addition, it should be possible to filter by the values ​​of the Personal model attributes
. for example, select everyone with the name Alexey who work in clinics with ID 5,14,34

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dialog, 2015-04-21
@HDAPache

If I understand correctly, then if you do it through a relation, then to solve the first part of the problem:
> How to select from the Personal model all those who are associated with one particular clinic, say with clinic_id = 5
relation must be built from the Clinic side and select all Personal
> And also it would be better not for one clinic ID, but for several at once ... If possible.
fetch value IN (x, y, z) and cycle through the models, calling relation
> In addition, it should be possible to filter by the values ​​of the attributes of the
model for example, select everyone with the name Alexey who work in clinics with ID 5,14,34 a
separate getter, I think.
For such operations, I would recommend looking all the same towards SQL queries :)

R
Ruslan, 2015-04-30
@mitrm

stuff.cebe.cc/yii2docs/guide-db-active-record.html

// find customers and bring back together their country and active orders
// SELECT * FROM `customer`
// SELECT * FROM `country` WHERE `id` IN (...)
// SELECT * FROM `order` WHERE `customer_id` IN (...) AND `status` = 1
$customers = Customer::find()->with([
    'country',
    'orders' => function ($query) {
        $query->andWhere(['status' => Order::STATUS_ACTIVE]);
    },
])->all();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question