【问题标题】:Laravel Left join not returing all records with where clauseLaravel Left join 不返回带有 where 子句的所有记录
【发布时间】:2020-05-28 21:05:56
【问题描述】:

我没有在左连接中获取所有记录。 我的核心查询就像SELECT cities.*, states.name as state FROM cities LEFT JOIN states ON cities.states_id = states.id 它运行良好

我的 laravel 查询是这样的

      $all_city = DB::table('cities')
            ->leftjoin('states', 'cities.states_id', '=', 'states.id') 
            ->where([['states.name', 'LIKE', '%'.$state.'%'], ['cities.name', 'like', '%'.$name.'%']])
            ->select('cities.*', 'states.name as state')
            ->orderBy($sort_field, $sort_type)
            ->paginate($pagination);
            return response()->json($all_city);

Laravel 只返回那些在两者中都是唯一的记录。如果我从中删除 where 子句,那么它运行良好。 有人可以建议出了什么问题。

提前致谢!!

【问题讨论】:

    标签: laravel


    【解决方案1】:

    我认为问题不在join子句中,而是在where子句中......

    where 子句采用三个参数,第一个为列,第二个为运算符,第三个为要比较的值...

    你应该把这个分开:

    ->where([['states.name', 'LIKE', '%'.$state.'%'], ['cities.name', 'like', '%'.$name.'%']])
    

    到:

    ->where('states.name','like','{$state}%')->where('cities.name','Like','%{$name}%');
    

    这篇文章解释了在 where 中使用 like:

    https://freek.dev/1182-searching-models-using-a-where-like-query-in-laravel

    【讨论】:

      【解决方案2】:

      你可以这样做:

      $all_city = DB::table('cities')
                      ->leftJoin('states', 'cities.states_id', '=', 'states.id') 
                      ->where('states.name', 'like', '%'.$state.'%')
                      ->where('cities.name', 'like', '%'.$name.'%')
                      ->select('cities.*', 'states.name as state')
                      ->orderBy($sort_field, $sort_type)
                      ->paginate($pagination);
             return response()->json($all_city);
      

      【讨论】:

        猜你喜欢
        • 2011-01-30
        • 2015-08-21
        • 2014-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-05
        相关资源
        最近更新 更多