phpyii2

Why is it 'id' equal to null in yii2


controller

After being saved, the ID is equal to the null in the batchInsert

$model= new Sale();
  
if($model->load(Yii::$app->request->post())) {
      $model->status=1;
      $model->price = str_replace(",","",$model->price);
      //$id = $model->id        
      $model->save();
      $id = $model->id; 
      if($model->pardakht == 1) {
          for($i=0;$i<$model->count;$i++) {
                $data[$i][0]=Yii::$app->request->post('number_check')[$i];
                $data[$i][1]=Yii::$app->request->post('price_check')[$i];
                $data[$i][2]=Yii::$app->request->post('date_check')[$i];
                $data[$i][3]=Yii::$id;
                $data[$i][4]=Yii::$model->customer_id;
          }               

          Yii::$app->db->creatCommand()->batchInsert('sale_check', [
              'number_check',
              'price_check',
              'date_check',
              'user_id',
              'customer_id'
          ], $data)->execute();
     }
}

var_dump($id);

$id = null ????????????


Solution

  • Your model has an error, to find where the problem and what attributes has error, Change this:

    $model->save();
    $id = $model->id; 
    

    to

    if($model->save()) {
        $id = $model->id;
        /** other codes ****/
    }else{
        var_dump($model->errors);
        /** or other usage of this array result **/
    }