我已完成了example中的所有操作。
但我不明白如何将id
字段保存到相关表中。我有两个表,公司和实体,有一对一的关系。它会保存我插入的所有字段,但不会保存company_id
和entity_id
。我需要使用aftersave吗?
在公司控制人员中:
public function actionCreate()
{
$model1=new Company;
$model2=new Entity;
if(isset($_POST['Company'], $_POST['Entity']))
{
// populate input data to $a and $b
$model1->attributes=$_POST['Company'];
$model2->attributes=$_POST['Entity'];
// validate BOTH $a and $b
$valid=$model1->validate();
//$valid=$model2->validate() && $valid;
if($valid)
{
// use false parameter to disable validation
$model1->save(false);
$model2->save(false);
// ...redirect to another page
}
}
$this->render('create', array(
'model1'=>$model1,
'model2'=>$model2,
));
}
在公司模型中:
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'=>array(self::HAS_ONE, 'Entity', 'entity_id')
);
}
答案 0 :(得分:2)
好的,当我们开始玩Yii时,这些都是正常的疑惑。我们来看看:
“规则”方法(在模型中)应仅用于由用户填充的列。在您的情况下,我猜“entity_id”由服务器处理,因此将其从“规则”中删除。使用该新配置,您可以在保存之前验证这两个对象。
如果验证成功,首先保存一个模型并使用其“id”保存另一个进行引用的模型。这样的事情:
public function actionCreate()
{
$model1=new Company;
$model2=new Entity;
if(isset($_POST['Company'], $_POST['Entity']))
{
// populate input data to $a and $b
$model1->attributes=$_POST['Company'];
$model2->attributes=$_POST['Entity'];
// validate BOTH $a and $b
$valid=$model1->validate();
$valid=$model2->validate() && $valid;
if($valid)
{
$model2->save( );
$model1->entity_id = $model2->id;
$model1->save( );
}
}
$this->render('create', array(
'model1'=>$model1,
'model2'=>$model2,
));
}