QSqlRelationalTableModel does not respect the foreign key rules in the database
-
I have a problem deleting data from a SQLite database. The problem is that data is deleted even if the database does not allow it. If I try to delete a record directly in the database, I get the message Error while deleting row from table exp_subcategory: FOREIGN KEY constraint failed. If I delete the same record from the data model with the command model.removeRow(row), the record is deleted without an error message being displayed. How can I stop this and prevent a record from being deleted that cannot be deleted according to the database?
Thanks!
-
@DagG
You are trying to delete a foreign key row to which the referencing table holds a reference. Right? The database detects that by examining the referencing table. To enforce it on your model you would either have to have all the referring table rows in memory and look through them or issue a query to the database to find out.QSqlRelationModel
is not designed for editing on the foreign table. It is intended just as a means of displaying the foreign values when viewing or editing the referring table. -
@JonB
OK, I understand. That means I shouldn't create the model with the QSqlRelationalTableModel but rather use the QSqlTableModel and then it should work, or do I still have to consider something else? To understand: Table_A has a foreign key from Table_B. I delete a record from Table_B using removeRow() and it works. Doing the same directly in the database produces the error I described above. -
Yes, so as described in my first post. If you are going to allow editing of the foreign table you have to deal with any referential integrity issues if you want to avoid an error at the database side. Or accept that it can error if the user deletes a row in B while there is some row somewhere in A which references it. report it to the user and take it from there.
-
1/7