Viewing relations in table views

The main feature of relational database is its ability to relate one or more tables. One such relating 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 QSqlTableModel, we will get a view as given in the following screenshot:

Viewing relations in table views

By using relational table model, we can reference the department and branch into their relations as follows:

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

This code will set the relations of department and branch column to their respective tables along with the column value that has to be displayed on the view. On setting the relations, the view will be modified as shown in the following screenshot where the ID's 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
3.135.216.75