Yii2高级在一个表单中显示和保存两个表的字段
Yii2 Advanced Displaying and Saving fields of two tables in one form
如何在一个表格中显示不同表格的字段并立即将其保存在数据库中...场景是当我要填写一个新表格时,这两个表格将合并到同一个表格中并且可能同时保存。第二个问题是,"form"的"id"(PK)会在保存后递增生成数字。问题是如何在保存时将 "form" 中的 "id"(PK) 的值复制到 "forminfo_info"(FK) 中...请在这方面寻求帮助..
你的很多问题都得到了真正的解释here in the Yii2 guide。
无论如何,这就是我要在您的 actionUpdate/actionCreate-controller 中尝试的方法。
(注意:此代码未经测试,因此可能需要一些修复,但整体结构应该可以正常工作。)
// Create empty models, typically for actionCreate()
$m1 = new Model();
$m2 = new AnotherModel();
// ...or load models using ids for actionUpdate($m1Id, $m2Id)
$m1 = Model::findOne($m1Id);
$m2 = AnotherModel::findOne($m2Id);
// Try to populate the models from the request
if ($m1->load(Yii::$app->request->post()) && $m2->load(Yii::$app->request->post())) {
// Models now loaded, but not validated
if ($m1->validate() && $m2->validate()) {
// Both models are now validated, save the first one
$m1->save(false); // No need to validate again
// Now Model has an id, save its id as a reference in AnotherModel
$m2->m1Id = $m1->id;
// ...or create a method in your Model-model for setting the foreign key
// $m2->connectModel($m1); // The fancier object oriented way
$m2->save(false); // Set true if you validate the foreign key
}
}
// Return view for rendering
如果两个保存操作中的任何一个失败(未在代码中测试),这是一个可能应该处理的致命错误。最坏的情况是您最终可能会保存一个模型而不是另一个模型,尽管如果验证通过则不太可能。如果您的数据库支持,请查看 "atomic" 保存(全部保存或不保存)的事务,或者只是保留它(我认为大多数只是保留它或记录错误供以后使用)。
如何在一个表格中显示不同表格的字段并立即将其保存在数据库中...场景是当我要填写一个新表格时,这两个表格将合并到同一个表格中并且可能同时保存。第二个问题是,"form"的"id"(PK)会在保存后递增生成数字。问题是如何在保存时将 "form" 中的 "id"(PK) 的值复制到 "forminfo_info"(FK) 中...请在这方面寻求帮助..
你的很多问题都得到了真正的解释here in the Yii2 guide。
无论如何,这就是我要在您的 actionUpdate/actionCreate-controller 中尝试的方法。 (注意:此代码未经测试,因此可能需要一些修复,但整体结构应该可以正常工作。)
// Create empty models, typically for actionCreate()
$m1 = new Model();
$m2 = new AnotherModel();
// ...or load models using ids for actionUpdate($m1Id, $m2Id)
$m1 = Model::findOne($m1Id);
$m2 = AnotherModel::findOne($m2Id);
// Try to populate the models from the request
if ($m1->load(Yii::$app->request->post()) && $m2->load(Yii::$app->request->post())) {
// Models now loaded, but not validated
if ($m1->validate() && $m2->validate()) {
// Both models are now validated, save the first one
$m1->save(false); // No need to validate again
// Now Model has an id, save its id as a reference in AnotherModel
$m2->m1Id = $m1->id;
// ...or create a method in your Model-model for setting the foreign key
// $m2->connectModel($m1); // The fancier object oriented way
$m2->save(false); // Set true if you validate the foreign key
}
}
// Return view for rendering
如果两个保存操作中的任何一个失败(未在代码中测试),这是一个可能应该处理的致命错误。最坏的情况是您最终可能会保存一个模型而不是另一个模型,尽管如果验证通过则不太可能。如果您的数据库支持,请查看 "atomic" 保存(全部保存或不保存)的事务,或者只是保留它(我认为大多数只是保留它或记录错误供以后使用)。