简体   繁体   English

Yii2 模型保存空值

[英]Yii2 model saves null values

I'm using REST POST request to create new row in my db, but it saves me null values instead values which I sent.我正在使用 REST POST 请求在我的数据库中创建新行,但它为我保存了空值而不是我发送的值。 So I tried to send PUT request to modify existing data, but it returned not modified row (like when I use GET).所以我尝试发送 PUT 请求来修改现有数据,但它返回了未修改的行(就像我使用 GET 时一样)。 Actually, GET request works fine实际上,GET 请求工作正常

CountryController.php :国家控制器.php :

<?php

namespace app\controllers;

use yii\rest\ActiveController;

class CountryController extends ActiveController
{
    public $modelClass = 'app\models\Country';
}

Model Country.php :模型 Country.php :

I tried to do this with another table without setting primaryKey here, but got the same result.我试图用另一个表来做到这一点,而不在这里设置主键,但得到了相同的结果。

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Country extends ActiveRecord
{
    public static function primaryKey()
    {
        return ['code'];
    }
}

Here is my table :这是我的表:

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 |
+------+----------------+------------+

Try to POST data :尝试发布数据:

标题

And get the result:并得到结果:

预览

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 |
+------+----------------+------------+

Also I tried to print request using print_r/die and got obvious correct result /vendor/yiisoft/yii2/rest/CreateAction.php我也尝试使用 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;
}

Preview response:预览回复:

打印结果预览

But this data didn't save to database correctly as I described above但是这个数据没有像我上面描述的那样正确保存到数据库中

load() method uses setAttributes() - Note, that the data being populated is subject to the safety check by setAttributes(). load()方法使用setAttributes() -请注意,正在填充的数据将受到setAttributes()的安全检查。 The assignments by default will only be done to the safe attributes. 默认情况下,只会对安全属性进行分配。 A safe attribute is one that is associated with a validation rule in the current $scenario. 安全属性是与当前$方案中的验证规则相关联的属性。 Add rules and it should work. 添加规则,它应该可以工作。

在您的表单模型类中,您必须使用

if (!$this->validate()) { return null; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM