user765368
user765368

Reputation: 20356

return query result only if value of field on associated model is not empty cakephp

Let's say I have ModelA and ModelB in a CakePHP application. The type of association between ModelA and ModelB is the following:

ModelA hasOne ModelB
ModelB belongsTo ModelB

I want a find() query on ModelA that should return something only if the number field of ModelB is not empty (return empty otherwise). I tried something like this but my ModelA and ModelB are still returned in the result of the query even if the number field of ModelB is empty:

$this->ModelA->find('first', array(
    'contain' => array(
        'Model B' => array(
            'conditions' => array(
                 'ModelB.number IS NOT NULL'
            )
        )
    ), 
    'conditions' => array(
        'ModelA.id' => 13
    )
));

As you can see above, I put the condition in the contain on ModelB. I hope it's clear enough what I'm trying to do here. Can anybody help?

Thank you

Upvotes: 1

Views: 1446

Answers (1)

thaJeztah
thaJeztah

Reputation: 29137

You should always check the queries that are executed by CakePHP. By enabling debug level 2, the SQL statements should be visible on your page.

In your case, I suspect the NOT NULL condition is not specified correctly. It should probably be like this;

$this->ModelA->find('first', array(
    'contain' => array(
        'Model B' => array(
            'conditions' => array(
                 'NOT' => array(
                     'ModelB.number' => NULL
                 )
            )
        )
    ), 
    'conditions' => array(
        'ModelA.id' => 13
    )
));

Upvotes: 1

Related Questions