Laravel how to get query with bindings?

前端 未结 14 717
小蘑菇
小蘑菇 2021-01-31 15:58

I have some query that I need to pass to another query using query builder

$query = DB::table(\'table\')->whereIn(\'some_field\', [1,2,30])->toSql();

Mode         


        
14条回答
  •  -上瘾入骨i
    2021-01-31 16:31

    You can define below code block as helper function and use wherever required. It will bind numeric as well as string value with quotations.

    public static function getSqlWithBindings($query)
    {
        return vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(function ($binding) {
            return is_numeric($binding) ? $binding : "'{$binding}'";
        })->toArray());
    }
    

    Example:

    $query = Document::where('model', 'contact')->where('model_id', '1');
    dd(Document::getSqlWithBindings($query));
    

    Output:

    "select * from `document` where `model` = 'contact' and `model_id` = 1"
    

提交回复
热议问题