title: How to insert fields from two models onto one form
body: <p>I have done everything like in this <a href="http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models/" rel="nofollow noreferrer">example</a>.</p>
  
  <p>But I don't understand how to save the <code>id</code> fields to the related tables. I have two tables, company and entity, with one to one relations. It saves all the fields that I inserted, but not <code>company_id</code> and <code>entity_id</code>. Do I need to use aftersave?</p>
  
  <p>In the Company controller:</p>
  
  <pre><code>public function actionCreate()
  {
      $model1=new Company;
      $model2=new Entity;
      if(isset($_POST['Company'], $_POST['Entity']))
      {
          // populate input data to $a and $b
          $model1-&gt;attributes=$_POST['Company'];
          $model2-&gt;attributes=$_POST['Entity'];
  
      // validate BOTH $a and $b
      $valid=$model1-&gt;validate();
      //$valid=$model2-&gt;validate() &amp;&amp; $valid;
  
      if($valid)
      {
          // use false parameter to disable validation
          $model1-&gt;save(false);
          $model2-&gt;save(false);
          // ...redirect to another page
      }
  }
  $this-&gt;render('create', array(
      'model1'=&gt;$model1,
      'model2'=&gt;$model2,
  ));
  }
  </code></pre>
  
  <p>In the Company model:</p>
  
  <pre><code>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(
          'entity'=&gt;array(self::HAS_ONE, 'Entity', 'entity_id')
      );
  }
  </code></pre>