Sign in to follow this  
slobon

QSqlRelationalTableModel is messing things up

Recommended Posts

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". 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. [Edited by - slobon on March 17, 2009 2:05:26 PM]

Share this post


Link to post
Share on other sites
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");


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this