Sql leftJoin查询使用laravel语法显示错误

时间:2017-04-17 13:33:29

标签: mysql sql laravel laravel-5

这是我用于左连接的查询,它工作正常但是当我将其转换为laravel语法时缺少某些东西。

要转换的查询是

$result = DB::select("select amenities.name as 
name,amenities.type_id,amenities.id as id, amenities.icon, rooms.id as status 
from amenities left join rooms on find_in_set(amenities.id, rooms.amenities) 
and rooms.id = $room_id and type_id !=4");

而我正在做这个

$result = DB::table('amenities')
            ->select('amenities.name as name', 'amenities.type_id' , 'amenities.id as id'
                , 'amenities.icon', 'rooms.id as status' )
            ->leftJoin('rooms', function ($join) {
                 $join->on('FIND_IN_SET(amenities.id, rooms.amenities)')
                      ->where('rooms.id' , '=', '$room_id')
                      ->where('type_id','!=', 4);
            })->get();

错误是

  

中的InvalidArgumentException   F:\ XAMPP \ htdocs中\ arheb \ Arheb \供应商\ laravel \框架的\ src \照亮\数据库\查询\ JoinClause.php   第79行:on子句没有足够的参数。

2 个答案:

答案 0 :(得分:1)

您的查询错误。我假设amenities.idrooms.amenities分别是amenitiesrooms表的属性。

  

MySQL FIND_IN_SET()返回字符串的位置,如果它在字符串列表中存在(作为子字符串)。

您需要在on()函数的第一个和第二个参数中传递列名。

$result = DB::table('amenities')
            ->select('amenities.name as name', 'amenities.type_id' , 'amenities.id as id'
                , 'amenities.icon', 'rooms.id as status' )
            ->leftJoin('rooms', function ($join) {
                 $join->on('amenities.id', '=', 'rooms.amenities')
                      ->where('rooms.id' , '=', '$room_id')
                      ->where('type_id','!=', 4);
            })->get();

答案 1 :(得分:0)

我想你可以试试这个:

$result = DB::table('amenities')
           ->select('amenities.name as name', 'amenities.type_id' , 'amenities.id as id'
               , 'amenities.icon', 'rooms.id as status' )
           ->leftJoin('rooms', function ($join) {
                $join->on(DB::raw("find_in_set(amenities.id, rooms.amenities)"))
                     ->where('rooms.id' , '=', '$room_id')
                     ->where('type_id','!=', 4);
           })->get();

希望这对你有用!