Unsolved 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 (); roles.clear(); 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)){ submitAll(); qDebug()<<"successful insertion" << lastError () ; database ().commit (); qDebug()<<database ().lastError (); } else { 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 ?
-
@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 whichlastError()
is being output when. You show the output all on one line, which implies it all comes fromqDebug()<<"successful insertion" << lastError () ;
; but I suspect the error part actually comes fromqDebug()<<database ().lastError ();
after thecommit()
, and the problem is as @jsulm observes. But without that clarification who knows.... -
-
@mnakhaei Well, I guess you first need to query for the tag and then use its ID
-
-
Presumably
activity.tagID
ought to be an auto-incrementing number in the database table definition? Or is thattags.id
? I get mixed up which way your tables relate. -
Insert the row into the table which auto-generates the ID.
-
Retrieve the auto-generated ID back from the database
INSERT
. -
Set the other table's new row's link column value to that ID.
-
Insert the row into the other table, containing the link column value.
-