skip to Main Content

I have a query that is not returning all the results it should.
I’m using Laravel, but the result is the same if I write the query directly in PHPMyAdmin:

clientpages::selectRaw('page as value, COUNT(ID) as `count`')
            ->where('page', 'like', '%blog%')
            ->orWhere('page', 'like', '%home%')
            ->whereBetween('date', [$range['from'], $range['to']]);

The problem is that the query only processes the first like. It only returns the pages that have blog in them and not the ones with home.
The culprit is the date condition. If I remove that, it works as expected, but what is the right way to use these three conditions all at once?

2

Answers


  1. Like you would wrap a normal SQL query in parentheses, you can do the same in Laravel like this:

    clientpages::selectRaw('page as value, COUNT(ID) as `count`')
                ->where(function($query) {
                    $query->where('page', 'like', '%blog%')
                    ->orWhere('page', 'like', '%home%')
                })
                ->whereBetween('date', [$range['from'], $range['to']]);
    
    Login or Signup to reply.
  2. $clientpages = DB::table('clientpages')
           ->where('page', 'like', '%blog%')
           ->orWhere('page', 'like', '%home%')
           ->whereBetween('date', [$range['from'], $range['to']])
           ->get(); //or count() if you just want the count
    
    clientpages::where('page', 'like', '%blog%')
               ->orWhere('page', 'like', '%home%')
               ->whereBetween('date', [$range['from'], $range['to']])
               ->get(); //or count() if you just want the count
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search