php - Laravel Join query Not work properly -


i trying list of users join query, not working properly. retrieve users except current user_id. pass in user_id exclude results return users , should have list of users except current user_id.

it returns row id value preferences table , not user table.

here query.

$query = db::table('users')            ->join('preferences', function($join) use($results) {               $join->on('users.id', '=', 'preferences.userid')                  ->where('preferences.classidfrom', '>=', $results->classidfrom)                 ->where('preferences.classidto', '<=', $results->classidto);          })            ->where('users.id', '!=',$userid)            ->wherenotin('users.id', $mid_query)            ->wherenotin('users.id', $last_query);  $result = $query->get(); 

if run query user_id of 22 result should not include user not work.

->where('users.id', '!=',$userid) 

again, result returns of columns user table correctly except id column value coming preferences table.

i think after join

                    ->where('users.id', '!=',$userid)                     ->wherenotin('users.id', $mid_query)                     ->wherenotin('users.id', $last_query); 

both 3 not work

if don't specify fields select, perform select *. when this, if multiple tables have same field name (e.g. id), ultimate value retrieved last table field. in case, preferences table comes after users table, fields same name in both tables end data preferences table.

the quick fix specify select statement:

$query = db::table('users')     ->join('preferences', function($join) use($results) {         $join->on('users.id', '=', 'preferences.userid')              ->where('preferences.classidfrom', '>=', $results->classidfrom)             ->where('preferences.classidto', '<=', $results->classidto);     })     ->where('users.id', '!=',$userid)     ->wherenotin('users.id', $mid_query)     ->wherenotin('users.id', $last_query)     ->select('users.*'); 

extra

if setup eloquent models , relationships, perform query eloquent orm.

$users = user::wherehas('preferences', function($query) use ($results) {     $query->where('classidfrom', '>=', $results->classidfrom)         ->where('classidto', '<=', $results->classidto); })     ->where('id', '!=',$userid)     ->wherenotin('id', $mid_query)     ->wherenotin('id', $last_query)     ->get(); 

additionally, clean where's little bit:

$ids = array_merge(array($userid), $mid_query, $last_query); $users = user::wherehas('preferences', function($query) use ($results) {     $query->where('classidfrom', '>=', $results->classidfrom)         ->where('classidto', '<=', $results->classidto); })     ->wherenotin('id', $ids)     ->get(); 

Comments