yii2yii2-modelyii2-active-records

Yii2: Multiple inverse relations to same model?


How do I handle multiple inverse relations pointing to the same active record? For example:

class Bicycle extends ActiveRecord {

    public function getFrontWheel() {
        return $this
            ->hasOne(Wheel::class, ['id' => 'front_wheel_id'])
            ->inverseOf('bicycles');
    }

    public function getRearWheel() {
        return $this
            ->hasOne(Wheel::class, ['id' => 'rear_wheel_id'])
            ->inverseOf('bicycles');
    }

}

class Wheel extends ActiveRecord {

    public function getBicycles() {
        return $this
            ->hasMany(Bicycle::class, ['???' => 'id'])
            ->inverseOf('??????');
    }

}

What can I do here? I critically need the inverse relations.


Solution

  • Here is my own solution. Key points:

    class Bicycle extends ActiveRecord {
    
        public function getFrontWheel() {
            return $this
                ->hasOne(Wheel::class, ['id' => 'front_wheel_id'])
                ->inverseOf('frontWheelBicycles');
        }
    
        public function getRearWheel() {
            return $this
                ->hasOne(Wheel::class, ['id' => 'rear_wheel_id'])
                ->inverseOf('rearWheelBicycles');
        }
    
    }
    
    class Wheel extends ActiveRecord {
    
        public function getFrontWheelBicycles() {
            return $this
                ->hasMany(Bicycle::class, ['front_wheel_id' => 'id'])
                ->inverseOf('frontWheel');
        }
    
        public function getRearWheelBicycles() {
            return $this
                ->hasMany(Bicycle::class, ['rear_wheel_id' => 'id'])
                ->inverseOf('rearWheel');
        }
    
    }