我正在尝试将记录插入QSqlRelationalTable
。如果之前调用setRelation
,则外键约束失败。
customers
表:
+-------------------+-------------+------+-----+---------+----------------+
| 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
表:
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(45) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
代码:
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();
输出:
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"