Coldfusion - 循环访问数据库查询结果时的可变字段名称 [英] Coldfusion - variable field name when looping through database query results

查看:28
本文介绍了Coldfusion - 循环访问数据库查询结果时的可变字段名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表中有一组列名 - 例如foo1、foo2、foo3、foo4.我想通过循环动态引用这些列名:

I have a set of column names in a table - e.g. foo1, foo2, foo3, foo4. I want to refer to these column names dynamically through a loop:

<cfloop index="i" from="1" to="4">
  <cfset foo = Evaluate("query.foo" & i)>
</cfloop>

上述方法不起作用 - ColdFusion 会抛出未定义变量"错误,即使 query.foo1 是对查询结果的有效引用.我还能怎么做?

The above doesn't work - ColdFusion throws a "variable not defined" error, even though query.foo1 is a valid reference to the query results. How else can I do this?

推荐答案

不要将 Evaluate() 用于类似的事情!它很慢,应该避免.

Don't use Evaluate() for things like that! It's slow and should be avoided.

<cfloop index="i" from="1" to="4">
  <cfset foo = query["foo" & i][query.CurrentRow]>
</cfloop>

或者,如果您愿意:

<cfloop index="i" from="1" to="4">
  <cfset foo = query["foo#i#"][query.CurrentRow]>
</cfloop>

Evaluate() 用于评估代码位.不要将它用于可以通过语言集成、更合适的方式更优雅地解决的事情.

Evaluate() is for evaluating bits of code. Don't use it for things that can be solved more elegantly in language-integrated, more appropriate ways.

使用尖括号"语法访问 Query 对象时,必须附加(基于 1 的)行号索引 (query["foo#i#"][RowNum]).使用传统的点"语法 (query.foo1) 时,当前行是隐式的.

When accessing Query objects with the "angle bracket"-syntax, you must append the (1-based) row number index (query["foo#i#"][RowNum]). When using the traditional "dot"-syntax (query.foo1), the current row is implicit.

要显式访问当前行,请使用 QueryObject.CurrentRow 属性.但它可以是直到 QueryObject.RecordCount 的任何正整数.建议对 CurrentRow 以外的任何内容进行范围检查.

To access the current row explicitly, use the QueryObject.CurrentRow property. But it could be any positive integer up to QueryObject.RecordCount. A range check is advised for anything other than CurrentRow.

这打开了一个有趣的领域:您可以开始使用带有随机访问"的查询对象.以前(在 CFMX 之前)你所能做的就是从头到尾迭代它们,取出你要找的东西.现在它就像一个嵌套的结构/数组数据结构,您可以以不同的方式使用.

This opens an interesting field: You can start to use query objects with "random access". Previously (before CFMX) all you could do was iterate them from start to end, pulling out the things that you look for. Now it's like a nested struct/array data structure that you can use in different ways.

这篇关于Coldfusion - 循环访问数据库查询结果时的可变字段名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆