OK I must be missing something really simple here. I just want to return all records from a table where the user_id matches (easy!) and the ‘paid’ field is either NULL or 0. My ‘paid’ field is a TinyInt (1).
My CakePHP model code is:
$workingRecord = $this->find('first',array(
'conditions'=>array(
'Subscription.user_id'=>$userId,
array('not' => array('Subscription.paid' => true)) // Not True, to catch both false or NULL values
)
));
The SQL generated by CakePHP is like this:
SELECT `Subscription`.`id`, `Subscription`.`paid` FROM `subscriptions` AS `Subscription` WHERE `Subscription`.`user_id` = 3 AND NOT (`Subscription`.`paid` = '1') LIMIT 1
Common sense would say this should work. The problem is that that SQL will return rows containing 0 in the ‘paid’ column, but will never return NULLs.
Is there any way to return zero’s and NULLs in the one stroke, without using ‘or’?
Thanks in advance.
If your field is TINYINT(1), you should not have any NULL values. If you do, run a quick query to replace any NULLs with the default, and set the database field to have a default of 1 or 0.
Then, your code should be:
Reason why it’s not working like you’d think:
According to MySQL’s documentation on ‘NOT’:
So – in your case, you’re saying
"NOT 1", which MySQL translates to" = 0".