Yii 1.1 - Many to Many Relationship - Returning data from relation table

482 views Asked by At

I have 3 tables in my database

tbl_products
product_id
default_price

tbl_packages
package_id
name

tbl_relations
relation_id
package_id
product_id
price

I have set up my many to many relationships successfully within my Package/Product models

//Product->relations()
'packages' => array(self::MANY_MANY, 'Package', 'tbl_relations(package_id, product_id)')

//Package->relations()
'products' => array(self::MANY_MANY, 'Product', 'tbl_relations(product_id, package_id)')

What I'd like to acheive is the ability to return tbl_relations.price instead of the tbl_products.default_price as each record can have a custom price. Can anyone point me in the right direction of how to do this?

I was thinking maybe I have to create a model for the relation and set up the relations with HAS_MANY and BELONGS_TO but I'm not sure if there is a better way. Thanks.

1

There are 1 answers

0
Wellso On

In the end I got the approach detailed in the question working. I created a model for the relation and returned packages/products along with the data within the relation

 //Package->relations()
'products' => array(self::HAS_MANY, 'PackageProductRelation', product_id))

//Product->relations()
'packages' => array(self::HAS_MANY, 'PackageProductRelation', package_id))

//PackageProductRelation->relations()
'products' => array(self::BELONGS_TO, 'Product', product_id))
'products' => array(self::BELONGS_TO, 'Package', package_id))