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'");

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值