Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a dynamic key name in a struct with cfquery column?

I have structure where I want to replace currentRow key with cfquery column recID. This column is integer that is auto incremented in sql table. For some reason my code is failing to create structure with unique key. Here is my code:

<cfquery name="qryAccounts" datasource="myDB">
   SELECT RecID, FirstName, LastName
   FROM Accounts WITH (NOLOCK)
</cfquery>

<cfloop query="qryAccounts">
    <cfset fnAccounts[RecID] = StructNew()>
    <cfset fnAccounts[RecID].RecordID = RecID>
    <cfset fnAccounts[RecID].FirstName = FirstName>
    <cfset fnAccounts[RecID].LastName = LastName>
</cfloop>

Code above produced this result:

[
  {
    "FIRSTNAME": "Mike",
    "LASTNAME": "Richards",
    "RECORDID": 1
  },
  null,
  null,
  null,
  {
    "FIRSTNAME": "John",
    "LASTNAME": "Matt",
    "RECORDID": 6
  }
]

Then I tried to do this:

<cfquery name="qryAccounts" datasource="myDB">
   SELECT RecID, FirstName, LastName
   FROM Accounts WITH (NOLOCK)
</cfquery>

<cfloop query="qryAccounts">
    <cfset fnAccounts["ID"&RecID] = StructNew()>
    <cfset fnAccounts["ID"&RecID].RecordID = RecID>
    <cfset fnAccounts["ID"&RecID].FirstName = FirstName>
    <cfset fnAccounts["ID"&RecID].LastName = LastName>
</cfloop>

And code above produced correct output:

{
  "ID1": {
  "FIRSTNAME": "Mike",
  "LASTNAME": "Richards",
  "RECORDID": 1
  },
"ID6": {
  "FIRSTNAME": "John",
  "LASTNAME": "Matt",
  "RECORDID": 6
  }
}

I'm wondering why first code is failing to produce correct output? Why second version with appended string works fine? Is there any way to fix or work around this problem?

like image 774
espresso_coffee Avatar asked Dec 11 '22 06:12

espresso_coffee


1 Answers

All you need to do is to define the variable fnAccounts as a structure.

<cfset fnAccounts = {}>

Without the definition, CF has the liberty to select whatever it seems fit.

<cfquery name="qryAccounts" datasource="myDB">
   SELECT RecID, FirstName, LastName
   FROM Accounts WITH (NOLOCK)
</cfquery>

<cfset fnAccounts = {}>
<cfloop query="qryAccounts">
    <cfset fnAccounts[RecID] = StructNew()>
    <cfset fnAccounts[RecID].RecordID = RecID>
    <cfset fnAccounts[RecID].FirstName = FirstName>
    <cfset fnAccounts[RecID].LastName = LastName>
</cfloop>

Since you are trying to use the RecID as an integer value key, it is similar to how we access an array (fnAccounts[1] first position in the array). Once you have defined fnAccounts as a structure, ColdFusion can look at the variable as a structure.

DEMO

like image 82
rrk Avatar answered Mar 16 '23 00:03

rrk