Identifying Relation (HAS_ONE)

Hello everybody,

i’m currently working on my first project with yii - so i’m new to yii.

The Problem i’m having at the moment is with a identifying relation and how to save it:

table 1: order

id (pk)




table 2: handOrder

orderId (pk,fk)





So i have one table where all orders go in with the data wich is similar for all the orders. depending on what kind of order it is, the details of the order go into another table. In this example this is only one table, the handOrder. An entry in the handOrder table only makes sence and can only exits with an entry in the order table (1:1 identifying relation).

I have defined this relation in the order model:

'handorder' => array(self::HAS_ONE, 'handOrder', 'orderId'),

My question now is, if it is possible to automaticly validate and save the related model, when the main model is saved? Or the other way round…validate and save the main model when the related model is saved. I don’t care.

Or is the only way to manualy save the other model?

Any hints would by appreciated.



If you are going to collect the input of both table in a single form, you can validate all field and then in your code manually set the foreign key field right before save.




If you collect the input of handorder in a different form, you will use a dropdown or something similar, and you can use CExixtValidatorfor validation.

The input of both tables is collected in a single form and the attributes are then populated like this:

$model = new Order();

$model->handorder= new HandOrder();



How do i now validate and save all the fields? Like this?:




$model->handorder = $order->primaryKey;


Or is there an "easier" solution to do this?



Your solution is the easiest possible, but has some mistake.

You are going to save even if the validation fails, and that is not what is expected to do.

Do like this:

$model = new Order();

$model->handorder= new HandOrder();

if (isset($_POST['order']))







	if ($valid)



		$model->handorder->order = $order->primaryKey;




So everithing will be correctly validate.

If you want an advice, work with error_reporting: E_ALL on your development machine, it really helps debug.

yeah, you’re right. i just wanted to know what to do at all.

There is just one line i don’t understand:

Shouldn’t it be

$model->handorder->orderId = $order->primaryKey;

? Or am I missing something?