【问题标题】:Yii2 Cannot insert attribute(FK) with id(PK)Yii2无法插入带有id(PK)的属性(FK)
【发布时间】:2016-07-23 17:11:36
【问题描述】:

我有来自模型/订单的 PK(Auto Inc) 与来自模型/预购的 FK id_order 关系的 ID,在我的 CRUD 操作(例如 actionCreate)中,我无法将属性预购插入表,因为来自订单的 id(PK)始终为空。我该如何解决这个问题?。

这是我的控制器

$cartPositions = Yii::$app->cart->getPositions();

  if (!$cartPositions or $cartPositions === null) {
      return $this->redirect(['index']);
  }

  $dataProvider = new ArrayDataProvider([
      'allModels' => $cartPositions,
  ]);

    $model = new Order();
    $model_po = new Preorder();
    $postData = Yii::$app->request->post();

        if ($model->load($postData) && $model_po->load($postData)) {
        //model->save(false);
        $model->status = 5;
        $model_po->id_order = $model->id;
        $model->total_cost = Yii::$app->cart->getCost();
        $model->date = date('Y-m-d H:i');
        $model->data = Yii::$app->cart->getSerialized();
        $model_po->name = $model->name;
        $model_po->phone = $model->phone;
        $model_po->remarks = $model->message;
        $model_po->created_at = $model->date;
        //$model_po->save();
        if (Model::validateMultiple([$model, $model_po]) && $model->save(false) && $model_po->save()) {
            Yii::$app->session->setFlash('success', 'Thank You');
            Yii::$app->mailer->compose('order/html', [
                'model' => $model,
                //'model_po' => $model_po,
                'dataProvider' => $dataProvider,
            ])
                //->setFrom(Yii::$app->params['email']['from'])
                // ->setTo(Yii::$app->params['email']['to'])
                // ->setSubject('The site posted a new order')
                // ->send();

                ->setFrom(Yii::$app->params['email']['from'])
                ->setTo(Yii::$app->params['email']['to'])
                ->setSubject('The site posted a new Preorder')
                ->send();

            Yii::$app->cart->removeAll();
            return $this->render('orderSuccess', [
                'model' => $model,
                //'model_po' => $model_po,
            ]);
        }
    } else
    {return $this->render('create_po', [
      'model' => $model,
      'model_po' => $model_po,
      'dataProvider' => $dataProvider,
    ]);}
  }

型号/订单

public function rules()
{
    return [
        [['status', 'total_cost', 'date', 'data', 'name', 'phone'], 'required'],
        [['code_order'], 'autonumber', 'format'=>'orderNum', 'digit'=>4],
        [['status', 'total_cost'], 'integer'],
        [['date'], 'safe'],
        [['data', 'message'], 'string'],
        [['name', 'email', 'phone'], 'string', 'max' => 255]
    ];
}

模型/预购

public function rules()
{
    return [
        [['id_order', 'address'], 'required'],
        [['id_order'], 'integer'],
        [['created_at', 'updated_at'], 'safe'],
        [['address', 'remarks'], 'string', 'max' => 500],
        [['id_order'], 'exist', 'skipOnError' => true, 'targetClass' => Order::className(), 'targetAttribute' => ['id_order' => 'id']],
    ];
}

错误信息:

违反完整性约束 – yii\db\IntegrityException SQLSTATE [23000]:违反完整性约束:1048 列 'id_order' 不能为空 正在执行的 SQL 是:INSERT INTO preorder (address, id_order, name, phone, remarks, created_at) VALUES ('', NULL, 'Name', '121324325' , '', '2016-07-23 17:01')

错误信息:数组 ( [0] => 23000 [1] => 1048 [2] => 列 'id_order' 不能为空

我尝试 getPrimaryKey() 并且最后插入 id() 不起作用,我尝试删除 $modelpo->id_order = $model->id 结果是两个表已填满但 id_order 为 0

【问题讨论】:

    标签: php mysql yii2


    【解决方案1】:

    $model->id 在 $model->save() 成功之前为空,因此您不应在此之前将其值分配给 $model_po->id_order。

    这是transaction 的好地方,因此您可以先验证数据,然后确保订单已保存,然后使用正确的 id_order 保存 Preorder。

    也可以看看link() 方法。

    【讨论】:

    • 非常感谢
    【解决方案2】:

    为什么不使用 afterSave()?绝对能解决你的问题

    【讨论】:

    • 谢谢。我现在使用事务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    相关资源
    最近更新 更多