mrateb
mrateb

Reputation: 2499

Yii2 - Using Junction table with relations

I have a table Book and a table Cover. The relation between Book and Cover is one-to-many, meaning that each book can have more than one cover. I thus have a third table connecting the two, book-cover-relation.

Translating those to models means I have 3 models,

Now In the Book model, I have the following relation for the related BookCoverRelations

public function getBookCoverRels() {
        return $this->hasMany(BookCoverRelation::className(), ['book' => 'id']);
    }

What I want though, is a to be able to get all the Covers. Is there way through which I can do this without first getting the relations and then iterating through them?

Upvotes: 0

Views: 493

Answers (2)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23738

You should create a relation with viaTable in Books Model

 public function getCovers(){
        return $this->hasMany( Covers::class,['id'=>'cover_id'])->viaTable('{{%book_cover_relation}}',['book_id'=>'id']);  
    }

and use it like

$qu = Books::findOne (['id'=>1]);

foreach($qu->covers as $cover){
    echo $cover->name;
}

Upvotes: 1

Fabrizio
Fabrizio

Reputation: 127

You can use viaTable() method to get all the Cover models "passing through" your BookCoverRelations junction table, as stated in the Definitive Guide to Yii 2.0: https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#junction-table

Upvotes: 1

Related Questions