conditions for accessors in Coldfusion ORM

回眸只為那壹抹淺笑 提交于 2020-01-15 05:21:06

问题


Once you have loaded a component are you then able to access properties of that object with set conditions? For instance, if you have a one-to-many relationship between people and pets, you load people specifying a particular person, you then want to pull all said persons pets where the pets are of a particular species. cats vs dogs for instance.

<cfset person=EntityLoad("person", {name="#URL.name#"})>
<cfset pets=person[1].getPets()>

is there anyway to call getPets where type='dog' or something?

Or would I have to loop through the pets creating structures for each type and deal with them that way?


回答1:


You should not loop through the pets if at all possible: distinguishing between types of pets is best left to the object that has a relationship with them or to a service that works with those objects.

One approach is to add a method to Person that will return a type of Pet. We're using something similar in our current project.

array function getDogs() {
    var HQL = "where petType = 'dog'";
    return ormGetSession().createFilter(this.getPets(),HQL).list();
}

You might also be able to make it more generic:

array function getPets( required string petType ) {
    var HQL = "where petType = '" & arguments.petType & "'";
    return ormGetSession().createFilter(this.getPets(),HQL).list();
}

Another approach is to use the where attribute in relationships in the Person object when retrieving pets. We use something like this as well:

property name="cats" type="array" fieldtype="one-to-many" cfc="model.Pets" fkcolumn="PERSON_ID" where="PET_TYPE = 'cat'" lazy="false";
property name="dogs" type="array" fieldtype="one-to-many" cfc="model.Pets" fkcolumn="PERSON_ID" where="PET_TYPE = 'dog'" lazy="false";

Note that these examples make several assumptions about the structure of your app and database: there is a Pets object in the model folder that maps to a table in your db; this table has a PET_TYPE column (that maps to a petType property) that contains pet types in lower case; the Person object maps to a table with a primary key called PERSON_ID, which is also a foreign key in the Pets table.

Also, when considering these and other approaches, you should think about how you intend to access pets. Turning off lazy loading can create performance hits if you have a significant number of Pets, particularly if there are several types you want to store (so you're making several passes through the Pets table when initializing a Person). You may not need separate properties if you don't access Pets often; it may be enough simply to have a getPets() function.



来源:https://stackoverflow.com/questions/6301745/conditions-for-accessors-in-coldfusion-orm

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