首页 > 解决方案 > 如何在 REST api (yii2) 中编写方法 create 按条件添加对象

问题描述

仅当尚未使用相同的登录名和号码时,我才想将新记录保存到数据库中。但是即使具有相同参数的记录已经存在,代码也会将其保存到db

我写 $model->save(); 在条件内,但无论如何它都会保存..整个控制器的代码

  <?php
namespace app\modules\api\controllers;
use yii\rest\ActiveController;
use app\models\Client;
class ClientsController extends ActiveController
{
    public $modelClass = 'app\models\Client';

      public function actionCreate(){
        $model = new Client();
        $login = $model->login;
        $carNumber = $model->carNumber;
        $result =null;
        if (!Client::findOne(['carNumber'=>$carNumber])){
            if(!Client::findOne(['login'=>$login])) {
                $model->save();
                $result = $model;
                return $result;
            }
            else {
                $result = "this login have been already used";
                return $result;
            }
        }
        else {
            $result = "this car number have been already used";
            return $result;
        }
    }
}

标签: phprestyii2

解决方案


您应该在模型规则中添加唯一验证:

    public function rules()
    {
    return [
        [['login','carNumber'], 'unique'],
    ];
    }

在 actionCreate 中,您应该通过 POST 请求传递您的属性,然后您的操作应该变为,例如:

public function actionCreate(){
    $model = new Client();
    if ($model->load(Yii::$app->request->post())) {
      if ($model->save()) {
        return $model;
        }
      return $model->errors; //or whatever you want
    }
}

延伸阅读:Yii2 输入验证


推荐阅读