D.R. D.R. - 2 months ago 9
PHP Question

Yii 2. Nested M to N relation

Question

I have multiple many-to-many relations. Is it possible to set relation via multiple junction tables (to 'tags' table form 'hospital')?

enter image description here

What do I have for now

I can set relation only via one junction table to 'treatments' table.

Hospital model

/**
* Getting treatments of the hospital record.
*
* @return ActiveQuery
*/
public function getTreatments()
{
return $this->hasMany(Treatment::className(), ['id' => 'id_treatment'])
->viaTable(HospitalTreatmentPrice::tableName(), ['id_hospital' => 'id']);
}

Answer

Now my Hospital model looks like this

class Hospital extends ActiveRecord
{
       /**
         * Getting treatments of the hospital record.
         *
         * @return ActiveQuery
         */
        public function getTreatments()
        {
            return $this->hasMany(Treatment::className(), ['id' => 'id_treatment'])
                        ->viaTable(HospitalTreatmentPrice::tableName(), ['id_hospital' => 'id']);
        }


        /**
         * Getting tags of the treatment.
         *
         * @return ActiveQuery
         */
        public function getTags()
        {
            return $this->getTreatments()->joinWith(Tag::tableName());
        }
}

and Treatment model

class Treatment extends ActiveRecord
{
    public static function tableName()
    {
        return 'treatments';
    }


    public function getTags()
    {
        return $this->hasMany(Tag::className(), ['id' => 'id_tag'])
                    ->viaTable(TreatmentTag::tableName(), ['id_treatment' => 'id']);
    }
}
Comments