Save related data


how can I save related data?

For example:

I have a model called Order and one called OrderLine which contains the lines for a customer’s order

Order HAS_MANY OrderLine

I figured

$order->order_lines[] = $order_line ;


would work to add a new line to the order

But it doesn’t

Similarily I figured that I could do

$order->customer = $customer when Order has a BELONGS_TO relationship with $customer

But that throws an excpetion.

How is that supposed to work?



I normally customize my AR model to handle this.

Pseudo code from the top of my head:


class Order extends CActiveRecord {




	protected function afterSave() { // invoked after the order instance is saved


		foreach($this->order_lines as $order_line) {

			$order_line->order_id = $this->id; // ensure to set the order id on each order line





then of course it’s a good idea to encapsulate your $order->save() in a transaction if you are using a transactional database engine in this case - it’s easy to forget about transactions when wrapping everything up like this ;)

This is what I intended to do as well.

My relation is called ‘order_lines’ though and therefore, I probably have to create a separate variable for this. If I use the same name as the relation I’m getting a ‘Modification of overloaded property has no effect’ warning

I guess this is because CActiveRecord’s __get() function doesn’t return by reference.

Maybe it would be good to change that.