Yii relation in relation and join table attributes

I have the following models: Products, Addons, AddonTypes, ProductAddons.

The schema is the following:

Product
id
name

Addons
id
name
type_id

AddonTypes
id
name

ProductAddons
id
product_id
addon_id
price

The question: how can I join these tables in relation to get the products simple like that

ProductAddons::model()->with('addons')->findAll() ?

Q1: Now I get the related addon but I cant figure out, how can I get the addon type? Q2: How can I get an attribute from a join table. Like the price from ProductAddons?

Upvotes: 0

Views: 267

Answers (1)

lin
lin

Reputation: 18392

I hope this will work for you. Using "with()" will always return an array. Also on 1:1 relations... its Yii ;).

/* @var $productsWithAddOnly ProductAddons */
$productsWithAddOnly = ProductAddons::model()->with('addons')->findAll();

if (!empty($productsWithAddOnly->addons) && is_array($productsWithAddOnly->addons)) {

    /* @var $addOn Addons */
    foreach ($productsWithAddOnly->addons as $addOn) {
       if (isset($addOn->type)) {
          var_dump($addOn->type);
       } 
    }
}

Btw. you should keep Model names singulary ...

Get all related models from products by:

$criteria=new CDbCriteria;
$criteria->with=array(
    'addons.addons',
);

$prdocutsWithAddOns = Product::model()->findAll($criteria);

Upvotes: 1

Related Questions