O'Reilly logo

CakePHP 2 Application Cookbook by Jorge González, James Watts

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

On-the-fly associations

Sometimes, you'll find it useful to create a new association on the fly before a find operation to retrieve specific data or filter unwanted result rows from your query.

In this recipe, we'll look at how associations can be defined at runtime on your models.

Getting ready

We'll assume you have the Package, Stock, and Warehouse models in place from our previous recipes, where Stock belongsTo Warehouse and Stock belongsTo Package.

We'll also add an active field to our packages and warehouses tables with the following SQL statement:

ALTER TABLE packages ADD active TINYINT(1) NOT NULL DEFAULT '1';
ALTER TABLE warehouses ADD active TINYINT(1) NOT NULL DEFAULT '1';

We want to retrieve only the stocks with a positive amount for both ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required