不解释QSqlRelationalTableModel是什么东西。看以下代码:
//3.1 创建model
model = new QSqlRelationalTableModel();
model->setTable("tyzb\_xmmx");
model->setFilter(filter);
model->setSort(tyzb\_xmmx::xh,Qt::AscendingOrder);
//3.2 外键列显示问题
model->setRelation(tyzb\_xmmx::dwdm\_id,QSqlRelation("dm\_dwdm","dwdm","dwmc"));
model->setRelation(tyzb\_xmmx::xmlb\_id,QSqlRelation("dm\_xmlb","xh","lbmc"));
model->setRelation(tyzb\_xmmx::zydm\_id,QSqlRelation("dm\_zydm","xh","zymc"));
model->setRelation(tyzb\_xmmx::zjxx\_id,QSqlRelation("tyzb\_zjxx","xh","zjxm"));
model->setJoinMode(QSqlRelationalTableModel::LeftJoin); //外键列为空的行也要显示
..........
其余的一些代码如设置列头显示、调整QTableView等都省略,然后调用以下代码:
//4 执行查询
QSqlRecord r = model->record();
QStringList fieldNames;
for(int i = ; i< model->columnCount();i++){
fieldNames.append( r.fieldName(i));
}
qDebug() << fieldNames.join(',');
model->select();
r = model->record();
fieldNames.clear();
for(int i = ; i< model->columnCount();i++){
fieldNames.append( r.fieldName(i));
}qDebug() << fieldNames.join(',');
查看下QDebug的输出:
"xh,createDate,bz,isDelete,lastOperate,bnd,jzsj,xmmc,nd,ndyq,qssj,xmbh,xmdm,xmsqs,yjnryq,yap,zszjyj,zgs,dwdm_id,xmlb_id,zjxx_id,gjz,zydm_id,zypx,hcmc"
"xh,createDate,bz,isDelete,lastOperate,bnd,jzsj,xmmc,nd,ndyq,qssj,xmbh,xmdm,xmsqs,yjnryq,yap,zszjyj,zgs,dwmc,lbmc,zjxm,gjz,zymc,zypx,hcmc"
发现什么了,外键所在列的列名已经被Select语句更新为外键显示列了,您如果在Select语句后还调用以下语句获取列序号,是会出错的,具体是返回-1:
model->fieldIndex("zydm_id"); //返回-1
作为对比,继续在执行过Select调用的model上调用:
r = model->record();
qDebug() << r.field(model->fieldIndex("zymc"));
qDebug() << r.field(model->fieldIndex("zymc")).value();
返回以下信息:
QSqlField("zymc", QString, length: , precision: , required: no, generated: yes, typeID: , autoValue: false, readOnly: false)
QVariant(QString, "集采中心")
也就是说,返回的是外键的显示值,而不是外键值本身。
那么,能否在model中直接获取原来的zydm_id值? 目前还没有发现好的办法,只有重新创建一个QSqlQuery语句,根据主键xh获取:
QSqlQuery getZydm(QString("select zydm\_id from tyzb\_xmmx where xh=%1").arg(r.value(tyzb\_xmmx::xh).toString()));
if(getZydm.first())
qDebug() << getZydm.value();
这时返回了外键的键值: QVariant(qlonglong, 7),
很不和谐优雅的办法啊! 暂时这样吧,有没有更好的请过客指点一二!
手机扫一扫
移动阅读更方便
你可能感兴趣的文章