Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top