Viewing relations in table views

The main feature of relational databases is their ability to relate one or more tables. One such relationship feature is the use of foreign key concept where a primary key of a table is related to a column in another table. This relation can be easily exhibited using QRelationalTableModel. In order to explain this, we create three tables that are connected to each other. The schema is defined as follows:

CREATE TABLE employee (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, name VARCHAR(40) NOT NULL, department INTEGER, branch INTEGER)
CREATE TABLE department (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, name VARCHAR(20) NOT NULL, FOREIGN KEY(id) REFERENCES employee)
CREATE TABLE branch (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL, name VARCHAR(20) NOT NULL, FOREIGN KEY(id) REFERENCES employee)

If we use the QSqlTableModel, we will get a view as given in the following screenshot:

Viewing relations in table views

Using relational table model, we can reference the department and branch into their relations, which is given as follows:

model.setRelation(2, QSqlRelation("department", "id", "name"));
model.setRelation(3, QSqlRelation("branch", "id", "name"));

This code will set the relation of department and branch column to their respective tables along with what column value has to be displayed on the view. On setting the relation, the view will be modified, as shown in the following screenshot, where the IDs are resolved into their respective names.

Viewing relations in table views

Thus, the relational model is so helpful in exhibiting relational databases.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset