Recursive Function in Coldfusion

做~自己de王妃 提交于 2019-12-22 13:52:35

问题


I'm trying to create a recursive function in coldfusion and am coming across some issues.

Here is the logic I have:

<cffunction name="getEvents" access="private">
  <cfargument name="strtdate">
  <cfargument name="parentID" default=0>
  <cfqeury name="qry" datasource="db">
    select *
    from table
    where parentid = #parentid# and 
          starttime between #strtdate# and #DateAdd('d', 1, strtdate)#
  </cfquery>

  <cfset events = arraynew(1)>
  <cfloop query="qry">
    <cfset events[qry.currentrow] = structnew()>
    <cfset events[qry.currentrow].id = qry.id>
    <cfset subevents = getEvents(strtdate, qry.id)>
    <cfif arraylen(subevents)>
      <cfset events[qry.currentrow].subevents = subevents>
    </cfif>
  </cfloop>

  <cfreturn events>
</cffunction>

The problem is that once the function calls itself once it looses the original query in the loop. I now the events are three level deep but I don't want to have to right up the same coded over and over to handle all the events.

I would like to end up with an array of structs that contains all the events and subevents for a given day.


回答1:


Try var scoping your query object. In fact you should use proper scoping in general. For example:

<cffunction name="getEvents" access="private">
  <cfargument name="strtdate">
  <cfargument name="parentID" default=0>

  <cfset var qry = "" />
  <cfset var events = "" />
  <!--- etc. --->


  <cfquery name="qry" datasource="db">
    select *
    from table
    where parentid = #parentid# and 
          starttime between #ARGUMENTS.strtdate# 
    and #DateAdd('d', 1, ARGUMENTS.strtdate)#
  </cfquery>

  ... etc.

Otherwise everything is going into the VARIABLES scope and overwriting others I suspect.

Hope that helps!

PS: You should also consider using <cfqueryparam /> in your queries.




回答2:


Make sure you var-scope your variables to keep them local to each invocation of the function.

In your function (at the top if in CF8 or earlier):

<cfset var qry = ''>
<cfset var events = ''>
<cfset var subevents = ''>


来源:https://stackoverflow.com/questions/3807871/recursive-function-in-coldfusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!