7

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.

0

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

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

3 Comments

I knew that I can do like this. But I want to know whether I can create direct relation or not.
I already tried it and it is working for tbl2 but it is not working for tbl3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.