Book Image

CakePHP 2 Application Cookbook

Book Image

CakePHP 2 Application Cookbook

Overview of this book

Table of Contents (20 chapters)
CakePHP 2 Application Cookbook
Credits
Foreword
About the Authors
About the Reviewer
www.PacktPub.com
Preface
Index

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 warehouses and packages that are active, so let's set amount for one join record, as shown in the following code:

UPDATE packages_warehouses SET amount = '1' WHERE id = 1;

Note that the ORM in CakePHP will translate the belongsTo associations to left...