Sanky
Sanky

Reputation: 397

Yii2: Relation through multiple via

I have a relation through multiple intermediate tables. How can I define in Yii2?

So for I have tried following

public function getTbl1()
{
    return $this->hasOne( Tbl1::className(), [ 'id' => 'tbl1_id' ] );
}

public function getTbl2()
{
    return $this->hasOne( Tbl2::className(), [ 'id' => 'tbl2_id' ] )->via( 'tbl1' );
}

public function getTbl3()
{
    return $this->hasOne( Tbl3::className(), [ 'id' => 'tbl3_id' ] )->via( 'tbl2' );
}

I get the relation tbl1 and tbl2, but not able to get the tbl3. How can I do it?

Thanks in advance.

Upvotes: 7

Views: 5251

Answers (2)

Yupik
Yupik

Reputation: 5031

Just tried this:

/**
 * @return ActiveQuery
 */
public function getLastPosition()
{
    return $this
                    ->hasOne(Position::class, ['equipment_id' => 'id'])
                    ->orderBy('date DESC');
}

/**
 * @return ActiveQuery
 */
public function getTest1()
{
    return $this->hasOne(CompanyCarpark::class, ['id' => 'company_carpark_id'])->via('lastPosition');
}

/**
 * @return ActiveQuery
 */
public function getTest2()
{
    return $this->hasOne(Company::class, ['id' => 'company_id'])->via('test1');
}

And it "worked like a charm". Check your keys in database, propably there's something wrong there.

Upvotes: 9

Alexey Berezuev
Alexey Berezuev

Reputation: 793

You should do it with parent-child structure, like this:

$model->find()
 ->with('relationOne') //Model1::getRelationOne(Model2::table_name()...)
 ->with('relationOne.childRelation'); // Model2::getChildRelation....

Upvotes: 2

Related Questions