Luis Masuelli
Luis Masuelli

Reputation: 12333

How do I add an item to a ManyToMany relationship?

Assume I have this model:

class Pizza extends CActiveRecord {
    //...
    public function relations() {
        return array(
            'toppings' => array(self::MANY_MANY, 'Topping', 'pizza_toppings(pizza_id,topping_id)')
        )
    }
    //...
}

And this other...

class Pizza extends CActiveRecord {
    //...
    public function relations() {
        return array(
            'pizzass' => array(self::MANY_MANY, 'Pizza', 'pizza_toppings(topping_id,pizza_id)')
        )
    }
    //...
}

And assuming the three tables exist (pizza, topping, pizza_toppings) in the database, with the specified fields for pizza_toppings.

I tried this:

$pizza = new Pizza();
$pizza->save(false);//save, no validate
$topping = new Topping();
$topping->save(false);//save, no validate
$pizza->toppings[] = $topping;

But when I add in that way, I get an E_NOTICE saying such assignment has no effect.

Q: How do I add in Yii 1.1.15 elements to the M2M relationship?

Upvotes: 0

Views: 39

Answers (1)

Nisic Jovan
Nisic Jovan

Reputation: 309

Try $pizza->toppings = array($topping);

If i remember correctly they forbid to add items manually but you can always change the whole array.

This is workaround solution and I guess it's not very clean, but it will do the job. If someone has a better solution please post.

I hope it helped

Upvotes: 1

Related Questions