1

I'm trying to insert a record to QSqlRelationalTable. If setRelation is called before, foreign key constraint fails.

customers table:

+-------------------+-------------+------+-----+---------+----------------+
| Field             | Type        | Null | Key | Default | Extra          |
+-------------------+-------------+------+-----+---------+----------------+
| id                | int(11)     | NO   | PRI | NULL    | auto_increment |
| name              | varchar(45) | YES  |     | NULL    |                |
| last              | varchar(45) | YES  |     | NULL    |                |
| email             | varchar(45) | YES  |     | NULL    |                |
| phone             | varchar(45) | YES  |     | NULL    |                |
| fax               | varchar(45) | YES  |     | NULL    |                |
| address           | text        | YES  |     | NULL    |                |
| customer_types_id | int(11)     | NO   | MUL | NULL    |                |
+-------------------+-------------+------+-----+---------+----------------+

customer_types table:

+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(45) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

Code:

model = new QSqlRelationalTableModel(this);
model->setTable("customers");
model->setRelation(7,QSqlRelation("customer_types", "id", "name"));
// ...
QSqlRecord record = model->record();
record.setValue("name",ui->lineEditName->text());
// Other fields
record.setValue(7,QVariant("1"));  // '1' exists in customer_types
qDebug() << model->insertRecord(-1,record);
qDebug() << model->lastError().text();

Output:

false 
"Cannot add or update a child row: a foreign key constraint fails 
(`doors`.`customers`, CONSTRAINT `fk_customers_customer_types` FOREIGN KEY 
(`customer_types_id`) REFERENCES `customer_types` (`id`) 
ON DELETE NO ACTION ON UPDATE NO ACTION) QMYSQL3: Unable to execute statement" 
4

0 回答 0