QSqlRelationalTableModel的Select语句会改变列的名字
不解释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 = 0; i< model->columnCount();i++){ fieldNames.append( r.fieldName(i)); } qDebug() << fieldNames.join(','); model->select(); r = model->record(); fieldNames.clear(); for(int i = 0; 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(0); qDebug() << r.field(model->fieldIndex("zymc")); qDebug() << r.field(model->fieldIndex("zymc")).value();
返回以下信息:
QSqlField("zymc", QString, length: 765, precision: 0, required: no, generated: yes, typeID: 253, 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(0);
这时返回了外键的键值: QVariant(qlonglong, 7),
很不和谐优雅的办法啊! 暂时这样吧,有没有更好的请过客指点一二!