我正在使用REST POST请求在我的数据库中创建新行,但它保存了空值而不是我发送的值。所以我尝试发送PUT请求来修改现有数据,但它返回的是未修改的行(就像我使用GET时一样)。实际上,GET请求工作正常
CountryController.php:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class CountryController extends ActiveController
{
public $modelClass = 'app\models\Country';
}
模型Country.php:
我尝试使用另一个表而不在此处设置primaryKey,但得到了相同的结果。
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Country extends ActiveRecord
{
public static function primaryKey()
{
return ['code'];
}
}
这是我的表格:
mysql> describe country;
+------------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+----------+------+-----+---------+-------+
| code | char(2) | NO | PRI | NULL | |
| name | char(52) | NO | | NULL | |
| population | int(11) | NO | | 0 | |
+------------+----------+------+-----+---------+-------+
mysql> select * from country;
+------+----------------+------------+
| code | name | population |
+------+----------------+------------+
| AU | Australia | 18886000 |
| BR | Brazil | 170115000 |
| CA | Canada | 1147000 |
| CN | China | 1277558000 |
| DE | Germany | 82164700 |
| FR | France | 59225700 |
| GB | United Kingdom | 59623400 |
| IN | India | 1013662000 |
| RU | Russia | 146934000 |
| US | United States | 278357000 |
+------+----------------+------------+
尝试发布数据:
得到结果:
mysql> select * from country;
+------+----------------+------------+
| code | name | population |
+------+----------------+------------+
| | | 0 |
| AU | Australia | 18886000 |
| BR | Brazil | 170115000 |
| CA | Canada | 1147000 |
| CN | China | 1277558000 |
| DE | Germany | 82164700 |
| FR | France | 59225700 |
| GB | United Kingdom | 59623400 |
| IN | India | 1013662000 |
| RU | Russia | 146934000 |
| US | United States | 278357000 |
+------+----------------+------------+
我还尝试使用print_r / die打印请求并获得明显正确的结果 的 /vendor/yiisoft/yii2/rest/CreateAction.php
public function run()
{
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id);
}
/* @var $model \yii\db\ActiveRecord */
$model = new $this->modelClass([
'scenario' => $this->scenario,
]);
$model->load(Yii::$app->getRequest()->getBodyParams(), '');
if ($model->save(false)) {
// PRINT THE REQUEST DATA
print_r(Yii::$app->getRequest()->getBodyParams());
die();
$response = Yii::$app->getResponse();
$response->setStatusCode(201);
$id = implode(',', array_values($model->getPrimaryKey(true)));
$response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));
} elseif (!$model->hasErrors()) {
throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
}
return $model;
}
预览回复:
但是如上所述,这些数据没有正确保存到数据库
答案 0 :(得分:3)
load()
方法使用setAttributes()
- 请注意,正在填充的数据受setAttributes()的安全检查。默认情况下,分配仅对安全属性进行。安全属性是与当前$方案中的验证规则关联的属性。添加规则,它应该工作。