M
M
Monitorkin2016-02-07 02:01:17
Yii
Monitorkin, 2016-02-07 02:01:17

(YII2) How to make autoincrement work when adding record to Mysql table?

There is:
table Test (id(AUTO_INCREMENT), text)
I do:

$test = new Test();
$test -> text = 'test1';
$test -> save();

I assume that an auto-increment value will be written to the id field, but no ... the record is not saved at all.
If you do this, then everything works:
$test -> id = 1;
$test -> text = 'test1';
$test -> save();

How to make it so that you do not explicitly specify the value of the id field?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Monitorkin, 2016-02-07
@Monitorkin

It turned out that the ID field was entered in the rules of the model (created via gii),
[['id', 'text'], 'required'], left it like this: [['text'], 'required'], it worked, thanks everyone!

V
Valery, 2016-02-07
@supervaleha

and in the DB is worth primary autoincrement? If the record is not saved - look (show) $model->getErrors() - we will be able to understand the reason for the non-saving.

3
333Serega333 333Serega333, 2016-02-07
@333Serega333

When creating a table, mark the required field as AUTO_INCREMENT

CREATE TABLE animals (id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL, PRIMARY KEY (id));
INSERT INTO animals (name) VALUES ("dog"),("cat"),("penguin"),
("lax"),("whale");

D
Dmitry Bay, 2016-02-07
@kawabanga

Use migrations, it's very easy to add and work with them. In this case, you will not have such problems.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question