Foreach内部查询Laravel时

时间:2018-02-09 16:59:14

标签: php mysql laravel laravel-5

嗨,大家好,这是我的功能,我正在使用laravel 5.3

public function search(Request $request){

    $word = $request->search;
    $status = explode(",", $request->status);
    $type = explode(",", $request->type);
    $beds = $request->beds;
    $baths = $request->baths;
    $amenities = explode(",", $request->amenities);
    $typeCount = 0;
    $amenitiesCount = 0;

    $query = DB::table('properties as pr')
        ->join('status as st', 'pr.status_id', '=', 'st.id')
        ->join('types as ty', 'pr.type_id', '=', 'ty.id')
        ->join('property_has_features as prfe', 'prfe.property_id', '=', 'pr.id')
        ->join('features as fe', 'prfe.feature_id', '=', 'fe.id')
        ->where('pr.title', 'like', '%'.$word.'%')
        ->when($status, function ($query) use ($status) {
            $statusCount = 0;
            foreach ($status as $v) {
                if ($statusCount > 0){
                    return $query->orwhere('st.title', $v);
                }

                return $query->where('st.title', $v); 
                ++$statusCount;
            }
        })->toSql();

    dd($query);
  }

}

我需要搜索多个值但是如果你搜索多个字段我有myqsl手册的查询但现在我转换为laravel但是咨询只在st.title的地方做一个虽然$ status是一个数组两个值或更多值永远不会成为if inner的时候,这是我为调试返回的咨询,任何帮助谢谢

"select * from `properties` as `pr` inner join `status` as `st` on 
`pr`.`status_id` = `st`.`id` inner join `types` as `ty` on 
`pr`.`type_id` = `ty`.`id` inner join `property_has_features` 
as `prfe` on `prfe`.`property_id` = `pr`.`id` inner join `features` 
as `fe` on `prfe`.`feature_id` = `fe`.`id` where `pr`.`title` 
like ? and `st`.`title` = ?"

2 个答案:

答案 0 :(得分:1)

闭包内的逻辑总是返回一个where() return $query->where('st.title', $v);

此外,您应该使用whereIn()而不是通过构建多个orWhere()子句来重新发明轮子:

->when($status, function ($query) use ($status) {
    return $query->whereIn('st.title', $status);
})

答案 1 :(得分:0)

如果您希望查询中的所有条件都为true以获得答案并使用多个where子句,并且如果您希望任何或某些条件为真,则可以使用{{1子句

whereOr
像这样