問題描述
假設(shè)我想顯示 type="color" 的完整獎項列表:
Let's say I want to show a full list of awards with type="color":
Awards Type 2013 Winner
====== ==== ===========
Blue Award color Tom
Red Award color
Green Award color Dan
為了達到這個結(jié)果,我可以在 Laravel 中進行這樣的查詢:
To achieve this result I could have a query in Laravel like this:
$year = '2013';
$awards = DB::table('awards')
->leftJoin('winners', function($join) use ($year)
{
$join->on('awards.id','=','winners.award_id');
$join->on('winners.year','=',DB::raw("'".$year."'"));
}
->where('awards.type','color')
->get();
如果您輸出 Laravel 生成的 SQL,您將看到只有 WHERE 子句 被參數(shù)化,并且 ON 子句 中的 $year 容易受到 sql 注入,如果我從不受信任的來源獲取它.此外,查詢的緩存潛力也會降低,因為 $year 會經(jīng)常更改.注意:如果您認為我只是將第二個左連接條件添加到查詢的 WHERE,這些不一樣.
If you output the SQL that Laravel generates you will see that only the WHERE clause is parameterized and $year in the ON clause is left vulnerable to sql injection if I get it from an untrusted source. Also the query's caching potential is reduced because $year will change often. Note: In case you were thinking that I just add the second left join condition to the WHERE of the query, these are not the same.
關(guān)于如何將查詢的 $year 部分參數(shù)化有什么想法嗎?
Any ideas on how to get the $year part of the query parameterized?
推薦答案
這里有一個奇怪的解決方法(不想擴展 Builder 和 JoinClause 類):
注意:這會破壞 ->
的查詢鏈,所以請注意 where
在下面被分隔.
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();
更新:泰勒添加 joinWhere
, leftJoinWhere
... 他說如果你有一個函數(shù)連接,只需使用 ->where
和 ->orWhere
從封閉內(nèi)."不過我還沒有嘗試過.
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.
這篇關(guān)于Laravel Eloquent/Query Builder 中 LEFT JOIN 的 ON 子句中的參數(shù)化查詢綁定的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!