I have tried to decipher the source code of Yii’s relational ActiveRecord which is a little too complicated for me to understand clearly. But it seems to me that it’s impossible to achieve your goal with Yii’s hasMany().
First to make clear what you want to do, I assume you also have a dog table? So do I understand correctly what you want is a relation from food to either cat or dog dependent on the prefix of the food_for column?
For Yii relations in general you need at least one key to build a relation, so you’d need a field in foods that specifies the type of animal. You could split up the food_for column into two columns: food_for (which would be “cat” or “dog”) and food_for_id which contains the primary key of the cat or dog table.
Your relation would be like this:
// inside the Cat model
public function getFoods(): ActiveQuery
{
return $this->hasMany(Foods::class, ['food_for_id' => 'id_cat'])
->onCondition("`food_for` = 'cat'");
}
I can’t change the tables, sadly. This confirms it can’t be done with a hasMany().
I’m going to search something with populateRelation() but that means i can’t use $model->foods, or i override __get() which scares me a little… (and i can say goodbye to ->with(‘foods’) )