如何在yii2.0中使用Active Record在数据库中保存两个表数据

时间:2015-02-09 09:38:32

标签: forms yii2

$model = new StickerOrder();
$model_shipping_address = new ShippingAddress();

这里贴纸订单表中有外键 - > shipping_address_id   我想首先将数据保存在shipping_address表中,然后保存在sticker_order表中。

3 个答案:

答案 0 :(得分:1)

首先保存送货地址:

$model_shipping_address = new ShippingAddress();

// Assign attributes here

if (!$model_shipping_address->save()) {
    // Failed to save shipping address

    return ...
}

然后将创建的送货地址的ID设置为贴纸顺序并保存:

$model_sticker_order = new StickerOrder();
$model_sticker_order->shipping_address_id = $model_shipping->id;

// Assign other attributes here  

if (!$model->save()) {
    // Failed to save sticker order

    return ...
}

不要忘记检查两种型号的成功节省

答案 1 :(得分:0)

这样做..

$model_shipping_address->attributes = $_POST[''];
$model_shipping_address->save();
if($model_shipping_address->save()) {
    $model->shipping_address_id = $model_shipping_address->id;
    $model->save()
return code
}

答案 2 :(得分:0)

$model = new StickerOrder();
$model_shipping_address = new ShippingAddress();

if(($model->load(Yii::$app->request->post()) && $model->save()) && ($model_shipping_address->load(Yii::$app->request->post()) && $model_shipping_address->save()) ){
//do something
}