Results 1 to 2 of 2

Thread: Determining Field Index in QSqlRelationalTableModel when Using QSqlRelation

  1. #1
    Join Date
    Sep 2025
    Posts
    1
    Qt products
    Qt5
    Platforms
    MacOS X Unix/X11 Windows

    Default Determining Field Index in QSqlRelationalTableModel when Using QSqlRelation

    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
    Attached Images Attached Images
    Attached Files Attached Files

  2. #2
    Join Date
    Jan 2026
    Posts
    1
    Qt products
    Qt4

    Default Re: Determining Field Index in QSqlRelationalTableModel when Using QSqlRelation

    Hello, to solve this, instead of relying on QSqlRelationalTableModel to resolve the foreign key column indices by name, you can iterate over the QSqlRecord Fields: You can iterate through the columns of the record to find the correct index for a foreign key. This is more flexible and avoids hardcoding field indices. Moreover, you can use the model's relation mappings (QSqlRelationalTableModel::relation) to determine which columns are foreign keys and handle them dynamically.

    Here’s an example of how you might adapt your code to reliably handle foreign key columns without hardcoding the field index:

    Qt Code:
    1. #include <QtSql/QSqlRelationalTableModel>
    2. #include <QtSql/QSqlRecord>
    3. #include <QtSql/QSqlRelation>
    4. #include <QDebug>
    5.  
    6. // Function to find the field index by name
    7. int getFieldIndexByName(QSqlRelationalTableModel* model, const QString& columnName) {
    8. int columnCount = model->columnCount();
    9. for (int i = 0; i < columnCount; ++i) {
    10. if (model->headerData(i, Qt::Horizontal).toString() == columnName) {
    11. return i;
    12. }
    13. }
    14. return -1; // Return -1 if not found
    15. }
    16.  
    17. // Sample code for inserting data and handling foreign key columns
    18. void insertData(QSqlRelationalTableModel* model, const QSqlRecord& record) {
    19. // Iterate over each field in the QSqlRecord to insert data
    20. for (int i = 0; i < record.count(); ++i) {
    21. QString fieldName = record.fieldName(i);
    22. int fieldIndex = getFieldIndexByName(model, fieldName);
    23.  
    24. // Check if the field is a foreign key reference
    25. if (fieldName.startsWith("ref_data_a")) {
    26. // Handle the foreign key column
    27. qDebug() << "Foreign key field:" << fieldName << "at index" << fieldIndex;
    28. // You can fetch the foreign key reference data here if needed
    29. }
    30. // Insert data into the field
    31. qDebug() << "Inserting value for field" << fieldName << "at index" << fieldIndex;
    32. model->setData(model->index(i, 0), record.value(i));
    33. }
    34.  
    35. // Try inserting the record
    36. if (!model->submitAll()) {
    37. qDebug() << "Error inserting record:" << model->lastError().text();
    38. }
    39. }
    40.  
    41. int main() {
    42. QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    43. db.setDatabaseName("testdb.db");
    44.  
    45. if (!db.open()) {
    46. qDebug() << "Database error:" << db.lastError().text();
    47. return 1;
    48. }
    49.  
    50. model.setTable("table_b");
    51.  
    52. // Setting relations for foreign keys
    53. model.setRelation(2, QSqlRelation("table_a", "id", "name")); // ref_data_a1
    54. model.setRelation(3, QSqlRelation("table_a", "id", "name")); // ref_data_a2
    55.  
    56. if (!model.select()) {
    57. qDebug() << "Model select failed:" << model.lastError().text();
    58. return 1;
    59. }
    60.  
    61. QSqlRecord record = model.record();
    62. record.setValue("some_data", "Test data");
    63. record.setValue("ref_data_a1", 1); // Example foreign key reference
    64. record.setValue("ref_data_a2", 2); // Example second foreign key reference
    65.  
    66. insertData(&model, record);
    67.  
    68. return 0;
    69. }
    To copy to clipboard, switch view to plain text mode 
    - Meredith - geometry dash

Similar Threads

  1. Refresh QSqlRelation
    By Banjo in forum Qt Programming
    Replies: 3
    Last Post: 23rd May 2018, 11:39
  2. Replies: 2
    Last Post: 14th April 2015, 21:50
  3. QSqlRelationalTableModel and autocomplete field
    By J03Bukowski in forum Qt Programming
    Replies: 1
    Last Post: 8th November 2012, 20:50
  4. Replies: 2
    Last Post: 22nd January 2009, 13:29
  5. Trouble with QSqlRelationalTableModel and QSqlRelation
    By yleesun in forum Qt Programming
    Replies: 0
    Last Post: 8th August 2008, 11:16

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.