Search code examples
cakephpcakephp-3.0nullablequery-buildercomparison-operators

not equals isnt working in cakephp3


I couldnt get the not equals condition to work. What happens is that it is ignoring all data as the cancelled_by field has been null. If the cancelled_by field is null then that does not equate to not equals Tutor.

This little error has cost me 5 days of wrong data. Is there a mistake I am making? Once I removed the not equals condition, all the data was retrieved as expected.

The 2 lines below is what I used and neither worked.

'Lessons.cancelled_by not like' => '%Tutor%'   

'Lessons.cancelled_by !=' => 'Tutor' 
$searchDate = date('Y-m-d');

$query3 = $this->find()
    ->contain([
        'Tutors', 'Subjects', 'Students', 'Students.Guardians', 'XeroInvoices'
    ])
    ->select([
        'Lessons.id', 'Lessons.lesson_date', 'Lessons.start_time', 'Lessons.end_time',
        'Tutors.id', 'Tutors.first_name', 'Guardians.id', 'Tutors.last_name',
        'Lessons.timesheet_status', 'Students.id', 'Students.first_name',
        'Students.last_name', 'Students.has_credit', 'XeroInvoices.invoice_number',
        'Guardians.guardian_email', 'Guardians.guardian_mobile',
        'Guardians.guardian_last_name', 'Guardians.guardian_first_name',
        'Lessons.due_date', 'Lessons.cancelled_by', 'Subjects.name', 'Lessons.revenue',
        'Lessons.discount', 'Lessons.surcharge', 'Lessons.future_makeup_lesson_id',
        'Lessons.cancelled_pastlesson_id'
    ])
    ->where([
        'Lessons.due_date' => $searchDate,
        'Lessons.lesson_inactive' => false,
        'Students.has_credit like' => '%postpaid%',
        'Lessons.cancelled_by !=' => 'Tutor'
    ])
    ->order([
        'Guardians.id',
        'Lessons.lesson_date' => 'ASC',
        'Lessons.start_time' => 'ASC'
    ])
    ->hydrate(false);

Solution

  • 'Lessons.cancelled_by !=' => 'Tutor' is correct but it wont work for null values. 'Lessons.cancelled_by IS NOT' => 'NULL' would work for NULL values instead. I think you can use both. So the result will only be (cancelled_by != 'Tutor' AND cancelled_by IS NOT NULL) which is the result you needed.