Thursday, March 16, 2017

Laravel where clause, and with a list of or's

I want to create a where clause that is an and, with a list of or's. Here's my code:

$searchLoop = array(
            'u.Name',
            'u.Email',
            'n.Name',
            'u.PhoneMobile'
        );    
$text = 'Manager';
$count = 0;
        foreach ($searchLoop as $loop) {
            $query->where(function ($where) use ($loop, $count, $text) {
                if ($count === 0) {
                    $where->where($loop, 'like', '%' . $text . '%');
                } else {
                    $where->orWhere($loop, 'like', '%' . $text . '%');
                }
            });
            $count++;
        }

Based on my reading of the laraval docs and some other searching, I would expect this to translate like so:

and  (
`u`.`Name` like '%Manager%'
or `u`.`Email` like '%Manager%'
or `n`.`Name` like '%Manager%'
or `u`.`PhoneMobile` like '%Manager%'
)

Instead, it translates to this:

and (`u`.`Name` like '%Manager%')
and (`u`.`Email` like '%Manager%')
and (`n`.`Name` like '%Manager%')
and (`u`.`PhoneMobile` like '%Manager%')

Further, it doesn't seem to matter how I play with the $where->where's within the $query->where function(whether I only do orWhere for every loop, etc), it still comes out with just the and's.

Thanks for the help in advance.



via Pete_1

Advertisement