QSqlRelationalTableModel的setFilter()问题




在使用QSqlRelationalTableModel时,可以设置外键,详细方法可以参考文档。

 

当使用了SqlRelationalTableModel的setRelation()后,再使用setFilter时就要注意了,因为SqlRelationalTableModel类中已经包含了多张表,所以在写过滤规则时,必须加上表名,否则会出问题,查不到任何结果。例如:filter = "myTable.id = 1",在id前面必须加上表名myTable.但是如果查询的被关联表,写表名貌似不好使,要写成relTblAl_n其中n是从1开始的编号,1是第一个关联表,以此类推。

 

贴一篇老外的文章:

 

As you know the QSqlRelationalTableModel class provides an editable data model for a single database table, with foreign key support.

 

 
model->setTable("employee");
model->setRelation(2, QSqlRelation("city", "id", "name"));
model->setRelation(3, QSqlRelation("country", "id", "name"));
 

In this example the setRelation() function calls establish a relationship between two tables. The first call specifies that column 2 in table employee is a foreign key that maps with field id of table city, and that the view should present the city’s name field to the user. The second call does something similar with column 3.

It was very easy and logical so far. However it gets more complicated if you want to set a filter to the relational table (e.g. filter the name of the country in your table view). So you would try to set the filter like this: setFilter(“country.name = ‘switzerland’”), but it’s not working.

 

Assuming you have read the Qt’s reference manual you know that Qt makes aliases to the relation table “The alias is is the relation’s table name and display column name joined by an underscore (e.g. tablename_columnname)”. So with that knowledge you might try to set the filter like this: setFilter(“country_name = ‘switzerland’”), but it’s not working either.

 

There must be somekind of bug because whatever you try the query keeps saying it’s an unknown column. However, if you have a look through the Qt’s Sql source code you will find a solution.

 

For the relation table name Qt uses aliases like relTblAl_2, where the number after the underscore is the foreign key column in the main table. So relTblAl_2.name is equal to city.name and relTblAl_3.name os equal to country.name.

 

 
model->setFilter("relTblAl_3.name = 'Switzerland'");

你可能感兴趣的:(sql,database,qt,库)