I am using a SQLite3 database with QSqlRelationalTableModel and QSqlRecord. I have configured a small test case that demonstrates the following issue:
I have a table that has 2 columns that reference (foreign key) the same column in another table. When I add the QSqlRelation to the QSqlRelationalTableModel, Qt effectively renames the column to include the foreign key reference. And this is adequately explained in the documentation.
My problem is that when I try to insert data into the model, I don't know how to reliably determine the field index for columns that are involved in a QSqlRelation. I do not want to hard code the field indexes in my code - I need to be able to refer to them by name.
I have not found a way to *reliably* get the field index using the column name if there are multiple foreign keys to the same "master" column. (Lines 90 and 91 in the attached main.cpp).
This is the output of the attached program:
Record Field ( 0 ): "id"
Record Field ( 1 ): "some_data"
Record Field ( 2 ): "table_a_name_2"
Record Field ( 3 ): "name"
Model Field ( "id" ): 0 , Record Field Index: 0
Model Field ( "ref_data_a1" ): -1 , Record Field Index: -1
Model Field ( "ref_data_a2" ): -1 , Record Field Index: -1
Column ( 2 ) Relation: [Table: "table_a" , Index Column: "id" , Display Column: "name" ]
Model Column: "table_a_name_2"
Record Column: "table_a_name_2"
Column ( 3 ) Relation: [Table: "table_a" , Index Column: "id" , Display Column: "name" ]
Model Column: "name"
Record Column: "name"
Record insert to table_b failed: "NOT NULL constraint failed: table_b.ref_data_a1 Unable to fetch row"
I have attached a sample project that includes:
testdb.zip - Zipped SQLite3 database
testdb.png - Image showing the database structure
main.cpp - Source code to connect to the database and try to insert data
CMakeLists.txt - Build script for the project
Bookmarks