Yii2 model saves null values

2019-08-01 13:37发布

问题:

I'm using REST POST request to create new row in my db, but it saves me null values instead values which I sent. So I tried to send PUT request to modify existing data, but it returned not modified row (like when I use GET). Actually, GET request works fine

CountryController.php :

<?php

namespace app\controllers;

use yii\rest\ActiveController;

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

Model 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

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

回答1:

load() method uses setAttributes() - Note, that the data being populated is subject to the safety check by 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.



标签: php yii2