2014-12-05 53 views
1

我有一些查询,我需要传递给另一个查询使用查询生成器Laravel如何获取绑定的查询?

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

Model::join(DB::raw("({$query}) as table"), function($join) { 
    $join->on('model.id', '=', 'table.id'); 
}) 

Select * from model join (select * from table where some_field in (1,2,30)) as table on model.id = table.id 

但绑定没有通过,这迫使我结果做这

$query = DB::table('table')->whereRaw('some_field in ('. join(',', [1,2,30]) .')')->toSql(); 

什么是有时不安全的。我怎样才能得到绑定的查询?

+0

是'some_field'一个整数?如果是这样,你可以使用'join(',',array_map('intval',[1,2,30]))'来确保数组只包含整数。 – Marwelln 2014-12-05 11:10:06

+0

验证不是这种情况。更多关于代码清晰度。 – 2014-12-05 11:18:38

回答

5

退房的getBindings()方法上Builder

getBindings()

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

$sql = $query->toSql(); 

$bindings = $query->getBindings(); 
-1

它是一切都在这里解释..... https://ajcastro29.blogspot.com/2017/11/laravel-join-derived-tables-properly.html

我创建了那件事一个范围查询。我认为它也可以在宏..

public function scopeJoinDerived($query, $derivedQuery, $table, $one, $operator = null, $two = null, $type = 'inner', $where = false) 
{ 
    $query->join(DB::raw("({$derivedQuery->toSql()}) as `{$table}`"), $one, $operator, $two, $type, $where); 
    $join = last($query->getQuery()->joins); 
    $join->bindings = array_merge($derivedQuery->getBindings(), $join->bindings); 

    return $query; 
}