Relations

Top  Previous  Next

Between two data sources, a relation can be set. The relation is used to define the "master-detail" relationship. For example, one record in the "Categories" table can have multiple entries in the "Products" table:

 

materDetailRelation

 

In order to create a relation, you need to indicate the following:

 

Parent table;
Child table;
Set of key columns in the parent table;
Set of key columns in the child table.

 

As an example, we will look at "Categories" and "Products" tables from the demo database. They have the following structure:

 

masterDetailTables

 

Both tables have got the CategoryID field, on which the relationship can be set. So, one category may contain several products.

 

How can related data sources be used in FastReport? There are two methods of doing this.

 

First method makes it possible to build reports of "master-detail" type. To do this, two "Data" bands are used. The master band is connected to the master data source, the detail band - to detail data source. Our example will be like this:

 

masterDetailReport

 

Such a report, if you run it, will print a list of products in every category:

 

masterDetailReportResult

 

The second method allows referring to the master from the detail data source. We will show this by an example. Let us say, we want to print a list of all the products. For this, we need one "Data" band, which is connected to the "Products" table:

 

relationReport

 

Such a report will print all the products from all the categories. Let us say, beside each product, we want to print a category name to which it belongs. Without using relation, this would have been harder. All we know about the product's category is its id (represented by "CategoryID" column in the "Products" table). Category name, which we would like to print, is stored in the "CategoryName" column of the "Categories" table. With the help of relation, we can refer to the name of a category in the following way:

 

[Products.Categories.CategoryName]

 

For the current row of the "Products" table, FastReport will find the corresponding parent row in the "Categories" table, and return a value of the "CategoryName" column.

 

In a general case, way of referring to a parent table field allows an unlimited number of table ancestors:

 

[Child_table.Its_parent.Parent_of_a_parent.And _so_on.Column_name]

 

To add such a data column into a report, open the "Products" table in the "Data" window. You will see that among its columns, there is a link to the "Categories" table:

 

relationInDataWindow

 

If we drag the column shown above into the report, then we will get a "Text" object with a text:

 

[Products.Categories.CategoryName]

 

Our report will be as follows:

 

relationReport1

 

If we run it, we will see the following:

 

relationReportResult