【问题标题】:Laravel Query Not work with where conditionLaravel 查询不适用于 where 条件
【发布时间】:2015-09-26 16:41:42
【问题描述】:

我正在尝试使用 where 条件获取我的查询结果。我当前的查询是

$last_query     = DB::table('user_matchs')->where('matched_user_id', '=', $UserId)->where('status','=','friend')->lists('user_id');
$mid_query      = DB::table('user_matchs')->where('user_id', '=', $UserId)->lists('matched_user_id');

$query = DB::table('users')
        ->where('id', '!=', $UserId)
        ->whereNotIn('id',$mid_query)
        ->whereNotIn('id',$last_query);  

$getchat_details = DB::table('preferences')->where('UserId', $UserId)->first();

if($getchat_details->ShowMan == 'true')
 { 
    $query->where('gender', '=', 'male');
}
else  { 
    $query->where('gender', '=', 'female');      
 }  

    $users = $query->get();

    return Response::json($users );


    }

在我的查询中,使用 if else 条件添加的条件不起作用

【问题讨论】:

  • 当你说它不起作用时,究竟是什么不起作用?如果您在$users = $query->get(); 之前执行var_dump($query->toSql());,它会输出什么?是否添加了 where 条件?
  • 使用$query->orWhere( 而不是$query->where(

标签: php mysql laravel laravel-4 laravel-5


【解决方案1】:

您可以预先确定要查询的性别。

if($getchat_details->ShowMan == 'true') { 
    $gender = 'male';
} else { 
    $gender = 'female';
}

$query = DB::table('users')
    ->where('id', '!=', $UserId)
    ->where('gender', $gender)
    ->whereNotIn('id',$mid_query)
    ->whereNotIn('id',$last_query);  

【讨论】:

  • 没有。不需要将where() 调用的结果分配给$query。调用该方法会更改实例本身。 $this 仅返回以使其易于链接。
  • @lukasgeiter 你说得对,我删除了无效的解决方案。
猜你喜欢
  • 1970-01-01
  • 2017-09-14
  • 2021-09-18
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 2015-02-19
  • 2021-10-14
  • 2016-11-06
相关资源
最近更新 更多