Can you use query builder to build a query with a

2019-03-02 10:10发布

问题:

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;
}

and then call DB::Query($SQL);

But this does not automatically protect the user input.

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?

回答1:

$query = $tableModel->newQuery();

foreach($items as $key => $val) {
    $query->where($key, "LIKE", '%'.$val.'%');
}


回答2:

foreach( $items as $key => $value )
{
    $query->where( $key, '=', $value );
}

Is something like that what you're after?

EDIT: Looks like Mark beat me to it.