例如,我有两个表。一个叫做";PedidoReserveQuarto";以及另一个";PedidoReservea";。我想做的是,当我点击按钮时,我想保存两个表中的数据。但首先我需要在表"中输入数据;PedidoReserveQuarto";因为id。
我的动作控制器
public function actionCreate($id)
{
$modelPedidoReservaQuarto = new PedidoReservaQuarto();
$modelPedidoReserva = new PedidoReserva();
$modelPedidoReservaQuarto->quartoId = $id;
$modelPedidoReservaQuarto->save();
if ($modelPedidoReserva->load(Yii::$app->request->post()) && $modelPedidoReserva->save()) {
return $this->redirect(['create', 'id' => $modelPedidoReserva->id]);
}
return $this->render('../pedido-reserva/create', [
'model' => $modelPedidoReserva,
]);
}
型号PeidoReserveQuarto
public function getPedidoReservas()
{
return $this->hasMany(PedidoReserva::className(), ['reservaQuartoId' => 'id']);
}
/**
* Gets query for [[Quarto]].
*
* @return yiidbActiveQuery
*/
public function getQuarto()
{
return $this->hasOne(Quarto::className(), ['id' => 'quartoId']);
}
PeidoReservea型号
public function getReservaQuarto()
{
return $this->hasOne(PedidoReservaQuarto::className(), ['id' => 'reservaQuartoId']);
}
假设表单中有模型所需的数据,并使用方法post发送这些数据(单击提交按钮(并且您必须从modelPedidoReservea获得id才能分配给modelPedido ReserveQuarto您可以尝试
public function actionCreate()
{
$modelPedidoReservaQuarto = new PedidoReservaQuarto();
$modelPedidoReserva = new PedidoReserva();
$modelPedidoReservaQuarto->quartoId = $id;
$modelPedidoReservaQuarto->save();
if ($modelPedidoReserva->load(Yii::$app->request->post()) && $modelPedidoReserva->save()) {
$modelPedidoReservaQuarto->load(Yii::$app->request->post());
$modelPedidoReservaQuarto->quartoId = $modelPedidoReserva->id;
$modelPedidoReservaQuarto-save();
}
return $this->render('../pedido-reserva/create', [
'model' => $modelPedidoReserva,
]);
}
一旦您保存了$modelPedidoReservea,相关id就已经可用。。