0
votes

Here is the scenario:

I have two tables:

family: id, name
person: id, name, familyId

The foreign key is on person (familyId -> family.id)

In my Person model i want to have a relationship that can include all the person entries that have the same familyId as the current person.

Essentially I want to do $person = Person::find([...])->with('family')->all() to get the current Person model, including an array of family members.

So far I have this on PersonModel:

public function getFamilyMembers()
{
   return $this->hasMany(Person::className(), ['familyId' => 'familyId']);
}

...

$person = Person::find()
            ->with('familyMembers')
            ->where(['id'=>1]);
foreach($person->family as $m) {
   var_dump($m);
}

I know I could do this with a junction table. But since it is a 1:n relationship I would like to avoid the extra Table.

Thanks.

1

1 Answers

0
votes

The fast decision is something like this query in your person model :

public function getRelatedPersons()
{
   return self::find()->jeftJoin(Family::tableName(), 'person.familyId =  
   family.id')->where(['person.familyId' => $this->familyId])->all();
}
...
foreach($personModel->relatedPersons as $person)  {
   var_dunp($preson);
}