Important: Please read the Qt Code of Conduct -

How insert data into QSqlRelationalTableModel that related into another table

  • I have QSqlRelationalTableModel that is model of "activity" table

    ActivityHandler::ActivityHandler(QObject *parent) :
        QSqlRelationalTableModel (parent,connection::getInstance ())
        setTable ("activity");
        setRelation (1,QSqlRelation("tags","id","name"));
        select ();
        for (int i = 0; i < columnCount(); i++)
            roles[Qt::UserRole + i + 1] = QVariant(this->headerData(i, Qt::Horizontal).toString()).toByteArray();
        setEditStrategy (QSqlRelationalTableModel::OnManualSubmit);

    and for inserting new data , i use this code ,

    void ActivityHandler::addSample()
        database ().transaction ();
        QSqlRecord r = record ();
        r.setValue ("name","en");
        r.setValue ("duration",30);
        r.setValue ("date","2018-07-18");    
        if(insertRecord(-1, r)){
            qDebug()<<"successful insertion" << lastError () ;
            database ().commit ();
            qDebug()<<database ().lastError ();
            qDebug()<< lastError ().text ();
            database ().rollback();

    its result is

    successful insertion QSqlError("19", "Unable to fetch row", "NOT NULL constraint failed: activity.tagID")

    how i can solve this problem ?

  • Lifetime Qt Champion

    @mnakhaei You apparently did not set tagID column value. tagID is defined as "NOT NULL", means it has to contain a value.

  • @mnakhaei
    You will do yourself & us a favor if your output makes clear just which lastError() is being output when. You show the output all on one line, which implies it all comes from qDebug()<<"successful insertion" << lastError () ;; but I suspect the error part actually comes from qDebug()<<database ().lastError (); after the commit(), and the problem is as @jsulm observes. But without that clarification who knows....

  • @jsulm activity.tagID have foreign key into , how can i fill this ? i have but for give tagID i should query to the database

  • Lifetime Qt Champion

    @mnakhaei Well, I guess you first need to query for the tag and then use its ID

  • @mnakhaei

    1. Presumably activity.tagID ought to be an auto-incrementing number in the database table definition? Or is that I get mixed up which way your tables relate.

    2. Insert the row into the table which auto-generates the ID.

    3. Retrieve the auto-generated ID back from the database INSERT.

    4. Set the other table's new row's link column value to that ID.

    5. Insert the row into the other table, containing the link column value.

Log in to reply