Model Relation

Hello,

  1. There is one form but two different models.

    public function actionCreate() {

        $model = new Vehicle;

        $purchaseModel= new Purchase;


        if (isset($_POST['Vehicle']) && isset($_POST['Purchase'])) {

          

            $purchaseModel->attributes=$_POST['Purchase'];


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

				

            if ($purchaseModel->save() )

                

                $model->save();

                $this->redirect(array('view', 'id' => $model->id));

        }


        $this->render('create', array(

            'model' => $model,

            'purchaseModel'=>$purchaseModel,

        ));

    }

  1. There is a relation define between the two models.

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'purchase' => array(self::BELONGS_TO, 'Purchase', 'purchase_id'),

		);

	}

3-everything save well, however purchase_id define in the vehicle model doesn’t update with the purchase id from the purchase table.

4.Expected results: when the forms get submitted, 1- both models save (vehicle and purchase) 2- the id in purchase will be tied or have a relation to the field purchase_id in vehicle.

Please see image for the relation definition.

  1. how do I go about defining such a relation, such as when saving both models, the purchase_ID in vehicle is a foreign key of the model purchase id.

Thank you

Hello yiilover the yii framework does not set the foreign key automatically. we have to set explicitly after the purchase model is saved like this




if ($purchaseModel -> save () )

{

$model->purchase_id=$purchaseModel->id;

$model -> save ();

}



There is also a great wiki article:

How to use a single form to collect data for two or more models

Thank you so much , that was a great and simple solution.

I have seen this article, it covers what I had in mind . Thank you so much.