douchun5969 2018-05-05 11:17
浏览 285

Yii2:使用ActiveRecord在数据库中重复行

i develop the product module that add product info into product table, i add the button at the top of my page that copy the current product , i want to duplicate the row of that product ( known by id ) in product table , i user activerecord to duplicate data bud the id always set null and my script cannot duplicate data , my script is :

$product_original = Product::findOne($id);
$product_copy = new Product();
$product_copy->attributes = $product_original->attributes
$product_copy->isNewRecord = true;
$product_copy->id = null;
$product_copy->save();

after save product $product->save(); always return false, please help me to solve my problem , thank alot :)

  • 写回答

1条回答 默认 最新

  • dpjuppr1361 2018-05-05 11:41
    关注

    You just need to copy attributes and that's it why are you assigning the $product_copy->isNewrecord and $product_copy->id=NULL;.

    The only reason the record is not saved is due to the validation error before saving the record you can check for errors if not saved

    Just use

    $product_original = Product::findOne($id);
    $product_copy = new Product();
    $product_copy->attributes = $product_original->attributes;
    if(!$product_copy->save()){
      //either print errors or redirect
      print_r($product_copy->getErrors());
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog