I think you want to explore the possibility of using the built-in function in the join clause ... your where clauses can collide with each other - and really you want the role_id clause to be in your connection.
http://laravel.com/docs/4.2/queries#joins
$clientId = 1; $name = 'Phillip'; $escaped = '%' . $name . '%'; $userList = DB::table('users') ->where('users.user_id', $clientId) ->where('firstname', 'LIKE', $escaped) ->orWhere('lastname', 'LIKE', $escaped) ->orWhere('email', 'LIKE', $escaped) ->join('users_roles', function($join) { $join->on('users.user_id', '=', 'users_roles.user_id') ->where('users_roles.role_id', '=', Role::USER_PARTICIPANT); })->get(); var_dump($userList);
The above query:
select * from `users` inner join `users_roles` on `users`.`user_id` = `users_roles`.`user_id` and `users_roles`.`role_id` = ? where `users`.`user_id` = ? and `firstname` LIKE ? or `lastname` LIKE ? or `email` LIKE ?
Which gives me one line back, given the following database:
mysql> desc users; +-----------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+------------------+------+-----+---------+----------------+ | user_id | int(11) unsigned | NO | PRI | NULL | auto_increment | | firstname | varchar(255) | NO | | NULL | | | lastname | varchar(255) | NO | | NULL | | | email | varchar(255) | NO | | NULL | | +-----------+------------------+------+-----+---------+----------------+ 4 rows in set (0.02 sec) mysql> desc users_roles; +---------+------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+------------------+------+-----+---------+-------+ | user_id | int(11) unsigned | NO | | NULL | | | role_id | int(11) unsigned | NO | | NULL | | +---------+------------------+------+-----+---------+-------+ 2 rows in set (0.03 sec) mysql> select * from users; +---------+-----------+------------+--------------------+ | user_id | firstname | lastname | email | +---------+-----------+------------+--------------------+ | 1 | Phillip | Harrington | philsown@gmail.com | +---------+-----------+------------+--------------------+ 1 row in set (0.00 sec) mysql> select * from users_roles; +---------+---------+ | user_id | role_id | +---------+---------+ | 1 | 1 | +---------+---------+ 1 row in set (0.00 sec)
source share