Parameterized query binding in ON clause for a LEFT JOIN in Laravel Eloquent / Query Builder

后端 未结 3 842
孤城傲影
孤城傲影 2021-01-14 02:21

Let\'s say I want to show a full list of awards with type=\"color\":

Awards        Type     2013 Winner
======        ====     ===========
Blue Award    colo         


        
相关标签:
3条回答
  • 2021-01-14 02:36

    This comes straight from the Laravel docs:

    The Laravel query builder uses PDO parameter binding throughout to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

    You shouldn't need to sanitize it at all. It should be fine. If you are worried about it though, you can use the Validator class to validate it however you want.

    0 讨论(0)
  • 2021-01-14 02:39

    Currently you can use $join->where:

    $year = '2013';
    
    $awards = DB::table('awards')
             ->leftJoin('winners', 
                   function($join) use ($year)
                   {
                        $join
                            ->on('awards.id','=','winners.award_id')
                            // "where" instead of "on":
                            ->where('winners.year', '=', $year);
                   }
             ->where('awards.type','color')
             ->get();
    
    0 讨论(0)
  • 2021-01-14 02:59

    Here's an odd work-around (didn't want to extend the Builder and JoinClause classes):
    Notice: This will break query chaining with -> so notice the where was seperated below.

    $query = DB::table('awards')
             ->leftJoin('winners', function($join)
                   {
                        $join->on('awards.id','=','winners.award_id');
                        $join->on('winners.year','=',DB::raw('?'));  
                   }
             ->setBindings(array_merge($query->getBindings(),array($year)));
    
    $query->where('awards.type','color');
    
    $awards = $query->get();
    

    UPDATE: Taylor added joinWhere, leftJoinWhere... he says that "if you have a function join just use ->where and ->orWhere from within the Closure." I've yet to try this though.

    0 讨论(0)
提交回复
热议问题