Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write an ORM statement to return filtered data from a data object?

Okay. I am just starting to use ORM in my Coldfusion applications. It has been going really well until now. I hit this snag. I have these two tables:

enter image description here

Here is the code that I am using to load data into the page. The second part of the if is the default load, and the first one is the one that is used to filter down the listings to a specific category.

<cfif form.filtercat neq ''>
    <cfset load = ormexecuteQuery('from product_spec_cats as cats inner join cats.product_spec_cat_prod_cat_lnk as link WHERE link.spl_prod_cat_id = #form.filtercat#',{},false)>
<cfelse>
    <cfset load = entityload('product_spec_cats')>
</cfif>

The cfelse query returns this which is exactly what I need:

enter image description here

The cfif query returns this which is a problem as there are two children in each parent array.

enter image description here

So, my question is, how do I write the HQL to return the data in the same structure as the default query and still be able to filter the data?

like image 769
Sollinger04 Avatar asked Apr 20 '26 11:04

Sollinger04


1 Answers

The HQL you are running is selecting both the product_spec_cats and product_spec_cat_prod_cat_link entities because you do not define what you want to select:

from product_spec_cats as cats 
inner join cats.product_spec_cat_prod_cat_lnk as link 
WHERE link.spl_prod_cat_id = #form.filtercat#

That query is essentially the same as a select * from ... in a normal SQL query. What you want to do is this:

select cats
from product_spec_cats as cats 
inner join cats.product_spec_cat_prod_cat_lnk as link 
where link.spl_prod_cat_id = #form.filtercat#

Depending on how your relationship is set up, you may not even need the inner join and you can write your query like this:

from product_spec_cats as cats    
where cats.product_spec_cat_prod_cat_lnk.spl_prod_cat_id = #form.filtercat#`

Finally, as an aside, I would recommend you use query parameters, especially when you are sticking something from the form scope into a query:

ormExecuteQuery("
    select cats
    from product_spec_cats as cats
    inner join cats.product_spec_cat_prod_cat_lnk as link
    where link.spl_prod_cat_id = :catID
", { catID = form.filtercat });
like image 127
Sean Walsh Avatar answered Apr 22 '26 19:04

Sean Walsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!