A
A
Artem Prokhorov2021-05-23 09:40:56
Yii
Artem Prokhorov, 2021-05-23 09:40:56

How to select the desired column from a related table in AR Yii2?

$arr = Menu::find()->with([
                'link' => function ($query) {
                    $query->select('menu_id, role_id');
                }
            ])->asArray()->all();


This is the link code in the model:
public function getLink()
    {
        return $this->hasMany(Menu_role::className(), ['menu_id' => 'id']);
    }


The problem with this example is that such a method obliges you to select the key by which the link was made (here it is menu_id).
That is, you don’t seem to get conditionally all 6 columns of the table, but you should always get the key, such a half-measure.

Maybe there is some other way to select in this case, or can this code be modified somehow?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Desh, 2021-05-28
@serdesh

$arr = Menu::find()
    ->with(['link'])
    ->select(['menu_role.menu_id', 'menu_role.role_id'])
    ->asArray()
    ->all();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question