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)

address

orderdate

orderstate

table 2: handOrder

orderId (pk,fk)

quality

color

tv

th

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.

cheers

Simon

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.




$order->save();

$handOrder->order=$order->primaryKey;

$handOrder->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();

$model->attributes=$_POST['order'];

$model->handOrder->attributes=$_POST['handOrder'];

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


$model->validate();

$model->handorder->validate();

$model->save();

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

$model->handorder->save();

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

Cheers

simon

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']))

{

	$model->attributes=$_POST['order'];

	$model->handOrder->attributes=$_POST['handOrder'];

	

	$valid=$model->validate();

	$valid=$model->handOrder->validate()&$valid;

	if ($valid)

	{

		$model->save();

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

		$model->handorder->save();

	}

}



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?