2014-12-05 55 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; 
}