简体   繁体   中英

conditions in contain cakephp find

is it good or bad practice in CakePHP to have conditions set in the contain of a find query like:

$data = $this->SomeModel->find('all', array(
    'contain' => array(
        'AnotherModel' => array(
            'conditions' => array(
                // some conditions
            )
        )
    )
));

In which cases will putting conditions inside a contain be useful, and when should I use it or not. Sorry, this is still confusing to me.

Thank you

I'm not sure whether this is a good idea... First of all, I'm going to assume that this specific case requires you to specify conditions that unique to this case, ie not general enough for you to put into your SomeModel model relationship criteria to AnotherModel .

My suggestions would be that you should put those conditions in your overall find conditions, as contain specifies which linked models to return (controlling the joins under the hood). Like in SQL, you can join another table and specify which records to match in your WHERE clause.

From the manual , you can specify conditions in your contain, but they won't affect the results that don't join your model like the overall conditions will.

I'd do this:

$data = $this->SomeModel->find('all', array(
    'contain' => array('AnotherModel'),
    'conditions' => array(
        // some conditions relating to AnotherModel
    )
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM