外键不存储相关模型的实际值

时间:2012-08-17 07:43:52

标签: php mysql yii relational-database

我正在Yii做一个小应用程序。因为我有这样的数据库

=============
 +   GROUP    +
 =============
 + id(pk)     +
 + name       +
 + description+
 ++++++++++++++


  =============
 +   MEMBERS  +
 ==============
 + id(pk)      +
 + group_id(fk)+
 + name        +
 + description +
 ++++++++++++++

Group model中的关系就像这样

public function relations()
  {
    return array(
      'members' => array(self::HAS_MANY,'Members','group_id'),
    );
  }

Members model中的关系就像这样

 public function relations()
  {
    return array(
      'group' => array(self::BELONGS_TO,'Group','group_id'),
    );
  }

根据要求我有rendered Members in Group model。所以我的controller for action create就像这样

    public function actionCreate()
  {
    $model=new Group;
    $members=new Members;
    // Uncomment the following line if AJAX validation is needed
     $this->performAjaxValidation($model);

    if(isset($_POST['Group'],$_POST['Members']))
    {
      $model->attributes=$_POST['Group'];
      $members->attributes=$_POST['Members'];
      $valid = $model->validate();
      $valid = $members->validate();
      if($valid)
      {
        $members->save(false);
        $group->save(false);
        $members->group_id = $model->getPrimaryKey();

        $model->save(false);
        $this->redirect(array('view','id'=>$model->id));
      }
    }
    $this->render('create',array(
      'model'=>$model,
      'members'=>$members,
    ));
  }

所以primarykey of Group model should be same as the forignkey of group_id in the members model就这样了。但它并没有像那样显示。group_id is remaining '0'每次都可以。有人告诉我这里有什么错误的部分吗?

1 个答案:

答案 0 :(得分:0)

您呼叫的$model->getPrimaryKey()

  • 首先,可以用作$model->primaryKey
  • 其次是返回尚未插入的新记录的主键,因此它没有。

在添加任何子项$group->save(false);之前保存父记录,但$group不是模型:)