QSqlRelationalModel Editable Issue
-
All,
I'm having an issue with a QSqlRelationalTableModel that I upgraded from a QSqlTableModel to get foreign key support.
m_model->setRelation(1, QSqlRelation("Insured", "ID", "Name"));
The code above works and my view is accurately displaying the Name field. The issue arises when I try to add a new record to my table. I'm now getting the below error message:
qt.sql.odbc: "QODBCResult::exec: Unable to execute statement:" Error: "[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'Name'. [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared."
Adding a qDebug statement in the InsertRowIntoTable(const QSqlRecord &values) method I see there is now a "Name" field for the relational table in the record which seems odd. The documentation notes that editable models are supported out of the box so I must be missing something.
QSqlRecord(25) 0: QSqlField("ID", int, tableName: "Policies", length: 10, required: yes, generated: no, autoValue: true, readOnly: false) "0" 1: QSqlField("Name", QString, tableName: "Insureds", length: 255, required: no, generated: yes, autoValue: false, readOnly: false) "TES0010"** 2: QSqlField("Status", QString, tableName: "Policies", length: 255, required: no, generated: yes, autoValue: false, readOnly: false) "Estimated" ...
-
Ah, found this issue right after posting while doing some more thorough review of my overridden methods. Hopefully it helps someone else.
For those converting QSqlTableModels to QSqlRelationalTableModels be careful what methods you're calling!
In the below code I forgot to update the base function call to QSqlRelationalTableModel so it was still calling QSqlTableModel::insertRowIntoTable(const QSqlRecord &values) which led to these issues.
bool PolicyModel::insertRowIntoTable(const QSqlRecord &values) { QSqlRecord rec = values; rec.setGenerated(Policy::DataRole::Id, false); return QSqlRelationalTableModel::insertRowIntoTable(rec); }
I had overridden this method because the primary key is an AUTO_INCREMENT field.
-