【问题标题】:cannot insert into the database in ActiveRecord Yii2无法在 ActiveRecord Yii2 中插入数据库
【发布时间】:2015-09-16 04:38:44
【问题描述】:

我不知道出了什么问题,但我无法插入数据库。

这是我在模型中得到的。

warranty.php

<?php

    namespace app\models;

    use Yii;
    use yii\db\ActiveRecord;
    use yii\behaviors\TimestampBehavior;
    use yii\db\Expression;
    use yii\helpers\VarDumper;
    /**
     * This is the model class for table "warrantytwo".
     *
     * @property integer $id
     * @property string $item_no
     * @property string $warranty_date
     * @property string $date
     * @property integer $created_by
     * @property string $tstamp
     */
    class Warrantytwo extends ActiveRecord
    {
        /**
         * @inheritdoc
         */
        public static function tableName()
        {
            return 'warrantytwo';
        }

        public function behaviors()
        {
            return [
                [
                    'class' => TimestampBehavior::className(),
                    'createdAtAttribute' => 'tstamp',
                    'updatedAtAttribute' => false,
                    'value' => new Expression('NOW()'),
                ],
            ];
        }

        /**
         * @inheritdoc
         */
        public function rules()
        {
            return [
                [['item_no', 'warranty_date'], 'required'],

                [['warranty_date', 'date'], 'string'],

                ['created_by', 'default', 'value' => 'none'],

                [['created_by'], 'integer'],

                [['warranty_date', 'date','tstamp'], 'safe'],

                [['item_no'], 'string', 'max' => 100]
            ];
        }

        /**
         * @inheritdoc
         */
        public function attributeLabels()
        {
            return [
                'id' => 'ID',
                'item_no' => 'Item No.',
                'warranty_date' => 'Warranty Date',
                'date' => 'Date',
                'created_by' => 'Created By',
                'tstamp' => 'tstamp',
            ];
        }

        public function addWarrantytwo()
        {
            if ($this->validate()) {
                $Warrantytwo = new Warrantytwo();
                $Warrantytwo->item_no = $this->item_no;
                $Warrantytwo->warranty_date = $this->warranty_date;
                $Warrantytwo->created_by = 'admin1';
                $Warrantytwo->date = date('Y-m-d H:i:s');
                //$Warrantytwo->touch('tstamp');

                if ($Warrantytwo->save()) 
                {
                    return $Warrantytwo;
                }else {
                    VarDumper::dump($Warrantytwo->getErrors());
                }
            }

            //return null;
        }
    }

controller.php

public function actionWarranty()
    {
        //$model= new WarrantyDate();
        $model= new Warrantytwo();

        if ($model->load(Yii::$app->request->post()) && $model->addWarrantytwo()) {
            return $this->redirect(['warranty']);
        } 
        else {
        return $this->render('warranty', [
            'model' => $model,
            ]);
        }
    }

在我看来/形式

 <?php $form = ActiveForm::begin([
      'id' => 'new-warranty-form',
      //'options' => ['class' => 'form-horizontal'], //for yii\ActiveForm
        'type' => ActiveForm::TYPE_HORIZONTAL, //for krajee\ActiveForm
        'formConfig' => ['labelSpan' => 4, 'deviceSize' => ActiveForm::SIZE_SMALL]  ]); ?>
                <div class="form-horizontal">

  <?= $form->field($model, 'item_no', 
        ['addon' => ['append' => ['content'=> '<a href="#w" onClick="sample()"><i class="glyphicon glyphicon-search"></i></a>']]    ]); ?>                          

    <?= $form->field($model, 'warranty_date')-> widget(DatePicker::classname(),
    [
    'options' => ['placeholder' => 'Date Claimed'],
    'pluginOptions' => [ 'autoclose'=>true ]
                ]); ?>

    </div>
    <div class="col-sm-offset-5 col-md-9">

     <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'warranty-button']) ?>

  <?= Html::resetButton('Reset', ['class' => 'btn btn-default']); ?>
     </div>

     <?php ActiveForm::end(); ?>

它没有给出任何错误,但是当我在数据库上检查它时,没有添加任何内容。我希望任何人都可以帮助我。谢谢你。我是 YII2 的新手,所以我还是不明白。

【问题讨论】:

  • 你能告诉我warranty_date post to action 的价值吗?
  • @gamitg 我认为值是一个日期。我使用了一个 kartik datepicker 小部件。我还将mysql中的数据类型更改为text而不是date,以确保可以在dbase中添加日期。
  • 您可以尝试使用$Warrantytwo-&gt;save(false)保存数据。这意味着没有验证保存数据以查找问题。
  • 在你的模型warrantyTwo.php函数addWarrantytwo()print_r($warrantytwo); exit(0);保存行上方,你会看到可能的错误
  • 我尝试使用您对 print_r 和 save(false) 的建议,但仍然没有。甚至错误。 :(@ankitraturi

标签: php mysql activerecord yii2


【解决方案1】:

由于您必须确定在什么情况下会出现问题,因此以这种方式进行测试。 (有时它会造成一些混乱,因为 validate() 总是返回一些东西)

    public function addWarrantytwo()
    {
        if ($this->validate()) {
            $Warrantytwo = new Warrantytwo();
            $Warrantytwo->item_no = $this->item_no;
            $Warrantytwo->warranty_date = $this->warranty_date;
            $Warrantytwo->created_by = 'admin1';
            $Warrantytwo->date = date('Y-m-d H:i:s');
            //$Warrantytwo->touch('tstamp');

            if ($Warrantytwo->save(false))   // try save without validation 
            {
                return $Warrantytwo;
            }else {
                VarDumper::dump($Warrantytwo->getErrors());
                exit;
            }
        }
        else {
            VarDumper::dump($this->validate());  // check for the correct flow
            exit;
        }

        //return null;
    }

【讨论】:

  • 您好,先生。我试过你的回答,表单提交后,我只得到一个“假”字。你认为错误在哪里?谢谢你的回答。 :)
  • 然后验证返回 false 。查找错误尝试有选择地评论您的规则。这将帮助您确定验证错误的原因。 ` [['warranty_date', 'date'], 'string'],` 日期字符串很奇怪。
  • 我想我知道错误在哪里。它是 created_by 的数据类型。但我会投票赞成你的回答,因为我发现它有助于找到错误发生的位置。谢谢!
  • 感谢您的支持。我希望这个答案有助于您找到错误。
  • 是的。很有帮助。 :) 事实上,我会将它用于一些调试目的。这样我就知道错误发生在哪里,在没有返回任何错误的验证规则中或在保存数据时,谢谢! :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 2015-02-05
相关资源
最近更新 更多