PDA

View Full Version : QSqlRelationalTableModel is messing things up after setting relation



slobo_n
17th March 2009, 21:14
Hi all.

First review the code that I'm using to create the tables.


void CreateTablesInSQLServer()
{
QSqlQuery createGroupsTbl("CREATE TABLE grupa_tbl("
"Grupa_Id int PRIMARY KEY IDENTITY(1,1) NOT NULL,"
"GrupaName varchar(30) NOT NULL UNIQUE);");


QSqlQuery createContactsTbl("CREATE TABLE contacts_tbl("
"contact_id int PRIMARY KEY IDENTITY(1,1) NOT NULL,"
"FirstName varchar(30) NULL,"
"LastName varchar(40) NULL,"
"Mobile varchar(40) NULL,"
"Phone varchar(40) NULL,"
"GrupaId int NOT NULL,"
"FOREIGN KEY (GrupaId) REFERENCES grupa_tbl);");
}





After that I'm creating the model and populate the model with data.

QSqlRelationalTableModel *model = new QSqlRelationalTableModel; //1
model->setTable("contacts_tbl"); //2
int i = model->fieldIndex("GrupaId"); //3
model->setRelation(i, QSqlRelation("grupa_tbl", "Grupa_Id", "GrupaName")); //4
QString TableName = model->tableName(); //5
model->select(); //6
int k = model->fieldIndex("GrupaId"); //7
int y = model->fieldIndex("LastName"); //8
model->setTable("contacts_tbl"); //9
int h = model->fieldIndex("GrupaId"); //10



This is the problem:
In line3 i can retrieve the field index for "GrupaId".
After i make the relation in line4 and i populate the model in line6, i cannot retrieve the field index for "GrupaId"(which is FOREIGN KEY) in line8. But i can get the field index for "LastName" and all of the rest columns.

If i call setTable in line9 i can retrieve the field index for "GrupaId", but as a result the relation in line4 is broken and i have to recreate it.

My goal is to retrieve the field index for "GrupaId" without calling

model->setTable("contacts_tbl");



again and again.


Thanks in advance.

slobo_n
18th March 2009, 21:26
I found the solution to my problem. To get the index of "GrupaId" after setting the relation in line4 I need to refer to "GrupaName" like this:

int r = model->fieldIndex("GrupaName");