Gimmly
Gimmly

Reputation: 463

What is the right way to write this query?

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?

Upvotes: 0

Views: 47

Answers (2)

Cameron
Cameron

Reputation: 554

$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

Upvotes: 1

shaedrich
shaedrich

Reputation: 5735

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']]);

Upvotes: 2

Related Questions