2

我在 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'每次。有人能告诉我这里有什么错误吗?

4

1 回答 1

0

$model->getPrimaryKey()您正在调用:

  • 首先,可以用作$model->primaryKey
  • 其次是返回一条新记录的主键,它还没有被插入,所以它没有。

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

于 2012-08-17T08:45:34.667 回答