首页 > 解决方案 > Laravel Left join 不使用 where 子句返回所有记录

问题描述

我没有在左连接中获得所有记录。我的核心查询就像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

解决方案


你可以简单地这样做:

$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);

推荐阅读