Mark
Mark

Reputation: 3271

Disabling join on CakePHP find function

Is there an easy way to disable the join for a find query in CakePHP

I have a Product model object that has a $belongsTo relation to User. My find query is:

$product = $this->Product->find('first',array(
    'fields' => array(
        'Product.name'
    ),
    'conditions' => array(
        'Product.active'=>1,
    ),

    'recursive' => false
));

The sql query that gets executes looks like this:

SELECT `Product`.`name` FROM `db`.`products` AS `Product` LEFT JOIN `db`.`users` AS `Owner` ON (`Product`.`owner_id` = `Owner`.`id`) LIMIT 1

Now I want to get rid of the join with users for performance reasons and since I don't use the data. Is there an easy way to do this? I hoped disabling recursive and manually setting the field argument would do the trick.

Upvotes: 2

Views: 1971

Answers (1)

Dave
Dave

Reputation: 29141

It's best practice (imo) to set public $recursive = -1; in your AppModel. This will get rid of the auto-magic finding that goes on, and will also allow you to use Containable whenever you need additional data without having to set recursive to -1 all over the place.

I believe in CakePHP 3+, they're going to get rid of recursive and make Containable on by default (just what I've heard - I haven't verified).

(If you REALLY don't want to set it everywhere, you can just set it immediately before the find - but... better to just set it in the AppModel and NEVER change it back)

Upvotes: 2

Related Questions