Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: Relation through multiple via

Tags:

php

yii2

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.

like image 686
Sanky Avatar asked Dec 09 '16 12:12

Sanky


People also ask

How to use yii2 model relation with multiple conditions?

Yii2 model relation with multiple conditions In AR Model Relations you can add multiple ON condition using andOnCondition method. public function getInvoiceItem(){ return $th...

Why does Yii use the together Query option?

For this reason, Yii provides the together query option so that we choose between the two approaches as needed. By default, Yii uses eager loading, i.e., generating a single SQL statement, except when LIMIT is applied to the primary model.

How do I force a single SQL statement when using Yii?

By default, Yii uses eager loading, i.e., generating a single SQL statement, except when LIMIT is applied to the primary model. We can set the together option in the relation declarations to be true to force a single SQL statement even when LIMIT is used. Setting it to false will result in some of tables will be joined in separate SQL statements.

How to post data using link tag in yii2?

In Yii2, you can post data using link tag in a form with  data- method post, you can also pass data as params. Example usage: ... Yii2 Dataprovider Default Sorting


1 Answers

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.

like image 165
Yupik Avatar answered Sep 20 '22 22:09

Yupik