There are 3 tables in the database

  1. Mobile operators

    mobile_operator

    id
    name -- Название

  2. Dedicated operator codes

    national_mobile_code

    id
    code -- Код

  3. Intermediate table where links are stored

    mo_nmc_keys

    id mobile_operator_id national_mobile_code_id

CRUD generated trace code

 <?php ... class MobileOperator extends \yii\db\ActiveRecord{ public function getMoNmcKeys(){ return $this->hasMany(MoNmcKeys::className(), ['mobile_operator_id' => 'id']); } ... } class NationalMobileCode extends \yii\db\ActiveRecord{ ... public function getRegNmcKeys(){ return $this->hasMany(RegNmcKeys::className(), ['national_mobile_code_id' => 'id']); } ... } class MoNmcKeys extends \yii\db\ActiveRecord{ ... public function getMobileOperator(){ return $this->hasOne(MobileOperator::className(), ['id' => 'mobile_operator_id']); } public function getNationalMobileCode(){ return $this->hasOne(MoNmcKeys::className(), ['id' => 'national_mobile_code_id']); } public function getMoNmcKeys(){ return $this->hasMany(MoNmcKeys::className(), ['national_mobile_code_id' => 'id']); } ... } 

How can I display the data with operator codes on the mobile operators page in GridView Or, in other words, how to get data through an intermediate table

    1 answer 1

    Better in the MobileOperator model MobileOperator use the link through the intermediate table and there is no need for an intermediate model.

     public function getNationalMobileCode() { return $this->hasMany(NationalMobileCode::className(), ['id' => 'national_mobile_code_id']) ->viaTable('mo_nmc_keys', ['mobile_operator_id' => 'id']); } 

    And then to get the codes you just need to perform

     $model = ... // Один из способов получения записи $national_mobile_codes = $model->nationalMobileCode; 
    • and how do I use the data in the gridview on the page mobile-operator\index.php to the operator corresponded his code. - Xfirab
    • Or is it possible to drive the data into $dataProvider - Xfirab
    • I tried in gridview add the line 'nationalMobileCode.code' to the columns but the data does not come out - Xfirab
    • at a minimum, this is a Многие-ко-Многим connection, respectively, as a result there will be an array that is simply not output via echo - lyhoshva
    • one
      you need something like this [ 'attribute' => 'national_mobile_code', 'value' => function ($model) { $codes = ArrayHelper::column($model->nationalMobileCode, 'code'); return implode(', ', $codes); } ], [ 'attribute' => 'national_mobile_code', 'value' => function ($model) { $codes = ArrayHelper::column($model->nationalMobileCode, 'code'); return implode(', ', $codes); } ], [ 'attribute' => 'national_mobile_code', 'value' => function ($model) { $codes = ArrayHelper::column($model->nationalMobileCode, 'code'); return implode(', ', $codes); } ], - lyhoshva