CFWheels – Find Through Association

When I first started learning CFWheels, I was so enamored with how simple it was to retrieve data from the database using the built-in ORM that I would code for days without taking full advantage of how much cleaner and simpler my code really could be. The more I worked with the ORM in Wheels, I learned more and more little tricks to help make my code much simpler. One of those tricks is to stop manually passing foreign keys into my find conditions and make the call through an association. Lets look at an example of how I used to do it.

Lets say we have a Project model that has many tasks and I want to retrieve all of the incomplete tasks for a given project.  Here are our two models:

Project.cfc

component name="Project" extends="Model" output="false" {

	public void function init() {
	  hasMany('Tasks');
	}

}

Task.cfc

component name="Task" extends="Model" output="false" {
	
	public void function init() {
	  belongsTo('Project');
	}

}

Now here is the controller with the old way of doing things:

component output="false" extends="Controller" {
	
	public void function show(){
		project = model('Project').findOneByKey(params.id);
		tasks = model('Task').findAll(where="projectid = #project.id# AND complete = false");
	}
	
}

Notice how I find the project I want and then pass the projectID in the task finder as the foreign key. Now this works, dont get me wrong. But there is a much cleaner way to do this.

component output="false" extends="Controller" {
	
	public void function show(){
		project = model('Project').findOneByKey(params.id);
		tasks = project.tasks(where="complete = false");
	}
	
}

By taking advantage of the relationships in our model, we can call the tasks through the project object and Wheels will automatically handle the foreign key relationship for us.

Isnt that much nicer?

Leave a Reply

Your email address will not be published. Required fields are marked *


*