php - 如何在 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;
}
}
}
解决方案
您应该在模型规则中添加唯一验证:
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 输入验证
推荐阅读
- python - 动画队列pygame
- xml - XSLT:XML 第一个属性需要转换为具有第二个属性值的元素
- c# - 你能帮我解析这个 JSON 吗?
- android - 更新到 'com.android.tools.build:gradle:4.1.0' 后无法更改依赖配置的解析策略
- c++ - 这种模板部分专业化背后的意图是什么?
- java - JPAMetaModelEntityProcessor 无法使用特殊字符正常工作
- python - Python - 下载的视频文件的编解码器问题
- java - 即使失去焦点,如何将分配的光标保留给 JDialog?
- vba - 访问不打印到选择的打印机
- r - 错误:XML 内容似乎不是 XML