displaying multiple models with conditions

I am using the following code to display multiple models in a view


public function actionDetail($id) {

  $model1=new model1;

  $model2 = new model2();


  $this->render('detail', array('model1'=>$this->loadModel($id, 'model1'),

    'model2'=>$this->loadModel($id, 'model2'))); 

}

It works great if both models have a matching id with a value.

However the two obvious problems are that:

  1. It will only render the page if model1 and model2 have matching ids with stored data. If model2 is a phone number for model1 of party and that party does not have a phone number no page is rendered.

  2. If the ids of records are not shared (same id number) between the two models then data will be mixed in the view. Model1.partyid ($id) should match Model2.partyid (FK).

How can I change my code to always display the content from model1 one and the proper content from model2 (associated through PK->FK relationship) if and only when there is associated data in that model?

You can place a if in the view.

You can try use relations:




class Model1 extends CActiveRecord {

...

public function relations() {

  return array(

    'model2' => array(self::HAS_ONE, 'Model2', 'model2_fk') 

  );

}

..

}


// usage into action

$model1 = $this->loadModel($id, 'model1');

$model2 = $model1->model2;



More on http://www.yiiframework.com/doc/guide/1.1/en/database.arr

@Weavora Team it looks like using relations is the way to go here.

I went to this in my controller




  $this->render('detail', array('model1'=>$this->loadModel($id, 'model1'),

    'model2'=>$model2));

and try to call it in the view




<?php echo $model->relation.of.model2;?>

And the only thing returned is Array. Guess I need to build that out.

I use giix and there is a similar implementation in there that uses relations to do what I am asking, but adds on links to the return values. Although useful I want to understand how to implement this without giix also.