Y
Y
Yuri Evstafyev2018-07-11 09:45:37
Yii
Yuri Evstafyev, 2018-07-11 09:45:37

Why does ActiveRecord->save() save fields as null?

The controller has this method:

public function actionAdd () {
        $req = json_decode(Yii::$app->request->getRawBody());
        $task = new Tasks();
        $task->name = $req->name;
        $task->save();
    }

As you can see, this method simply saves the new model to the database. Here is the model itself:
class Tasks extends ActiveRecord {
    
    public $name;
    
}

And her migration for MySQL:
class m180710_143740_create_tasks_table extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->createTable('tasks', [
            'id' => $this->primaryKey(),
            'name' => $this->string(),
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropTable('tasks');
    }
}

That is, in fact, there is nothing complicated here. However, when I try to add a new entry, the save() method keeps the fields blank. At the same time, there are no errors, and the method with save (false) also does not work. In the model object itself, the name attribute contains data, but it is still not saved.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2018-07-11
@yevstafyev

1. If the ActiveRecord attributes are taken from the database, they do not need to be separately declared as class properties
2. Where are the validation rules in the model?

A
abdujabbor1987, 2018-07-11
@abdujabbor1987

try adding rules for your model

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question