我正在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'
每次都可以。有人告诉我这里有什么错误的部分吗?
答案 0 :(得分:0)
您呼叫的$model->getPrimaryKey()
:
$model->primaryKey
在添加任何子项$group->save(false);
之前保存父记录,但$group
不是模型:)