2017-06-06 118 views
1

我有c ffunction應該返回JSON結構。有超過50列,我不得不返回。我不想手動構建我的結構,而是想動態構建它。因此,首先循環查詢,然後遍歷每個表列。下面是例子:如何從cfquery構建結構?

 <cffunction name="getRecords" access="remote" output="true" returnformat="JSON"> 
      <cfargument name="userID" type="string" required="true"> 

      <cfset fnResults = StructNew()> 

      <cfquery name="myQuery" datasource="test"> 
       SELECT 
        ur_first, 
        ur_last, 
        ur_dob, 
        ur_gender, 
        ur_email, 
        ur_address, 
        ... and the rest of the columns 
       FROM Users 
       WHERE ur_id = <cfqueryparam value="#trim(arguments.userID)#" cfsqltype="cf_sql_char" maxlength="15"> 
       ORDER BY ur_createDt 
      </cfquery> 

      <cfset fnResults.recordcount = myQuery.recordcount>  

      <cfloop query="myQuery"> 
       <cfset qryRecs = StructNew()> 
       <cfloop array="#myQuery.getColumnList()#" index="columnName"> 
        <cfset qryRecs.'#columnName#' = URLEncodedFormat('#columnName#')> 
       </cfloop> 
      </cfloop> 

      <cfset fnResults.data = qryRecs> 

      <cfreturn fnResults> 
    </cffunction> 

此錯誤Ajax調用之後,我的背:

CFML variable name cannot end with a &quot;.&quot; character. 
The variable qryRecs. ends with a &quot;.&quot; character. You must either provide an additional structure key or delete the &quot;.&quot; character. 

引用這一行:

443 : <cfset qryRecs.'#columnName#' = URLEncodedFormat('#columnName#')> 

我想設置列名構建qryRecs像這樣:

<cfset qryRecs.ur_first = URLEncodedFormat(myQuery.ur_first)> 

這樣我就不必手動設置50個加列。他們都應該動態創建。如果有人能幫助請讓我知道。

+2

嘗試將該行寫爲''不確定是否這是問題,但是此語法無論如何,這將是首選。 –

+0

[搜索檔案](https://stackoverflow.com/search?q=%5Bcfusionfusion%5D+dynamic+query+row)。動態訪問查詢列時有很多線程。也就是說,一個結構只適用於包含單個行的查詢。如果它包含多行,則使用結構數組。另外,不要忘記'var/local'所有函數變量 - 包括查詢名稱和索引變量(「列」)。 – Leigh

回答

3

我創建了ArrayCollection object,它可以將ColdFusion查詢轉換爲幾種不同的JSON格式。看一看,看看這是否符合你的需求。

例如,下面的查詢:

<cfquery name="rs.q" datasource="cfbookclub"> 
    SELECT DISTINCT 
     bookid, 
     title, 
     genre 
    FROM 
     books 
    WHERE 
     title LIKE <cfqueryparam value="%#arguments.term#%" cfsqltype="cf_sql_varchar" /> 
    ORDER BY 
     genre, title 
</cfquery>

將被轉換爲這個JSON:

{ 
    "data": [ 
     { 
      "bookid": 8, 
      "genre": "Fiction", 
      "title": "Apparition Man" 
     }, 
     { 
      "bookid": 2, 
      "genre": "Non-fiction", 
      "title": "Shopping Mart Mania" 
     } 
    ] 
}

我也在努力,增加了元數據的返回信息的更新:

{ 
    "success": true, 
    "message": "Array Collection created.", 
    "meta": { 
     "offset": 0, 
     "pageSize": 0, 
     "totalRecords": 0 
    }, 
    "data": [] 
};