Containing associated tables automatically

in CakePHP


Say you have OrdersTable associated to CustomersTable, and you want every order you select to automatically contain the corresponding customer information. (So that you don't have to do ->contain('Customers') on each find() call.)

There are two ways to accomplish this.

  1. In your OrdersTable:

    public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
    {
        $query->contain('Customers');
        return $query;
    }
  2. Use a custom finder

Further reading:

#cakephp #cakephp-orm