Support the ongoing development of Laravel.io →
posted 9 years ago
Database

I need to write a where clause with Query Builder with nested AND/OR, I suppose that I have to use whereNested() but I have not understood how to do.

An example of the where clause is

 WHERE ( ( ( date_start_month < 5 AND date_start_year = 2015 ) OR date_start_year < 2015 ) AND date_end_month = 5 AND date_end_year = 2015 )

how should I set this clause using QB?

Last updated 2 years ago.
0

You need to nest a function each time you want some brackets in your query, like this (untested)...

$query
  ->where(function($startQuery) {
    $startQuery
      ->where(function($thisYearQuery) {
        $thisYearQuery
          ->where('date_start_month', '<', 5)
          ->where('date_start_year', 2015);
      })
      ->orWhere('date_start_year', '<', 2015);
  })
  ->where('date_end_month', 5)
  ->where('date_end_year', 2015);
Last updated 9 years ago.
0

Thank you.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Kumidan kumidan Joined 29 Apr 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.