PDA

View Full Version : QSqlRelationTableModel - how to obtain foreign key value



Lesiok
8th October 2008, 07:49
I have QSqlRelationTableModel and need to get foreign key value fo record not the value from related table. Is this possible with Qt classes ?

yuriry
8th October 2008, 08:35
This method may help you:



QSqlTableModel * QSqlRelationalTableModel::relationModel ( int column ) const

Lesiok
8th October 2008, 09:31
This method may help you:



QSqlTableModel * QSqlRelationalTableModel::relationModel ( int column ) const


I know this method but how can I obtain correct record from this model ?

yuriry
8th October 2008, 16:32
After getting a related model you can obtain an index using QAbstractItemModel::index and data using QAbstractItemModel::data. I hope the row number is the same as in the original model.

Lesiok
8th October 2008, 18:54
After getting a related model you can obtain an index using QAbstractItemModel::index and data using QAbstractItemModel::data. I hope the row number is the same as in the original model.
Unfortunately no. QSqlRelationalTableModel::relationModel represents related table in database and it have number of rows equel to number of records in this table.
I think that this is not trivial problem because SELECT statement constructed in QSqlRelationalTableModel::selectStatement method remove all columns which are foreign keys to another tables.
In example.
Main table people with columns name, surname, town_id.
Related table towns with columns name, id.

After :

QSqlRelationalTableModel model( parent, db);
model.setTable("people");
model.setRelation( 2,QSqlRelation("town", "id","name") );


SELECT statement looks like :


SELECT "people"."name","people"."surname","relTblAl_3"."name" FROM "people","towns" "relTblAl_3" WHERE ("people"."town_id"="relTblAl_3"."id") ORDER BY "people"."name" ASC

yuriry
8th October 2008, 20:01
Yeah, you are right, it might not be possible to get foreign key :( (unless the display column is also unique so that you can search the related model, but this is not a very good option). Frankly, I do not even use standard models while working with databases, only custom ones sub-classed from QAbstractItemModel...