您可以在运行时在laravel中使用查询生成器来构建带有动态WHERE子句的查询吗? [英] Can you use query builder to build a query with a dynamic WHERE clause at runtime in laravel?
本文介绍了您可以在运行时在laravel中使用查询生成器来构建带有动态WHERE子句的查询吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我知道如果我构建一个动态SQL字符串,我可以执行以下操作
So I know if I build a dynamic SQL string I can do something like the following
$SQL = "SELECT * FROM " . $table;
$first = 1;
foreach($items as $key => $val)
{
if($first) $SQL .= " WHERE ";
else $SQL .= " AND ";
$SQL .= $key . " LIKE " . $VAL;
$first = 0;
}
,然后调用 DB :: Query($ SQL);
但这不会自动保护用户输入.
But this does not automatically protect the user input.
如果我在laravel中使用查询生成器,则将自动清除用户输入,但是我不知道如何在运行时使用查询生成器创建具有动态数量的where子句的查询.这可能吗?
If I used the Query Builder in laravel the user input would automatically be cleaned but I do not know how I can use the Query builder to create a query with a dynamic number of where clauses at runtime. Is this possible?
推荐答案
$query = $tableModel->newQuery();
foreach($items as $key => $val) {
$query->where($key, "LIKE", '%'.$val.'%');
}
这篇关于您可以在运行时在laravel中使用查询生成器来构建带有动态WHERE子句的查询吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文