HasMany with OR condition

I have two models Owner and Animal. Animal have 3 owners. I nead to write relation function. I try:

public function getAnimals() { $this->hasMany(Animal::className(), [])-> ->orOnCondition(['owner_1'=>'id']) ->orOnCondition(['owner_2'=>'id']) ->orOnCondition(['owner_3'=>'id']); }

and I get

SELECT * FROMownersLEFT JOINanimalsON ((owner_1='id') OR (owner_2='id')) OR (owner_3='id')

‘id’ in query is a string, not a variable name. How to do this?

API > ActiveQuery > onCondition()

Note that this condition is applied in case of a join as well as when fetching the related records. Thus only fields of the related table can be used in the condition. Trying to access fields of the primary record will cause an error in a non-join-query.

So you can’t set a condition that compares ‘owner_N’ of animal and ‘id’ of owner in orOnCondition.

IMO, you will have to give up the idea of defining a HasMany relation like this, and come up with some workaround.

If I were you, I would consider introducing a junction table that defines owner-animal relationship, i.e., HasMany relation via junction table. It’s much simpler.