PDA

View Full Version : [QSqlRelation] Is this possible?



mhbeyle
29th November 2009, 15:08
I have a model under QSqlRelationalTableModel that joins two tables. Primary table has an Id that point two a primary key in the secondary table. Secondary table has two fields that fill a name (name & surname).
When I set the relation I have this QSqlRelation definition:

QSqlRelation::QSqlRelation ( const QString & tableName, const QString & indexColumn, const QString & displayColumn )

With this I can only add one field to the model when I need two fields. Is possible make a model based on QSqlRelationalTableModel that returns two fields for an unique Id?

wysota
29th November 2009, 15:26
Each relation substitutes a foreign key with a value from another table. You can have as many relations in the table as many foreign keys. Thus if you have one foreign key, you can "import" only one field. In your case it would probably be best to make a view in the database out of those two tables or to use QSqlQueryModel.

mhbeyle
29th November 2009, 16:54
Each relation substitutes a foreign key with a value from another table. You can have as many relations in the table as many foreign keys. Thus if you have one foreign key, you can "import" only one field. In your case it would probably be best to make a view in the database out of those two tables or to use QSqlQueryModel.

Yes. QSqlQueryModel is the best solution for relations one-to-many but this model is read-only and I need to write extra code that is not necessary with RelationalTableModel.
I was longing a solution inside the QSqlRelationalTableModel component but I believe that I will have to write more lines of code. :rolleyes:

Thanks.

schnitzel
29th November 2009, 19:14
I ran into the same issue and ended up using QSqlQuery like this:



QSqlQuery q;

q = db.exec("SELECT a.ID, a.name, a.surname FROM addresses as a WHERE a.ID=" + your_id);

q.next();
thename = q.value(1).toString();
thesurname = q.value(2).toString();


I haven't tested this code, but I'm sure you get the idea.
The various sql models are great for certain scenarios but I find myself often using QSqlQuery in addition to the model, especially when the model is read-only.

hope this helps.