Reputation: 2761
I have a DB::select()
query where I want to add dynamic SQL by variable.
This is what I'm trying to do but it returns SQL syntax error.
$restaurantSql = "";
$restaurantIds = [6,43,51];
if ($someOtherVariable) {
$restaurantSql = "AND orders.restaurant_ids IN (".implode(",", $restaurantIds).")";
}
$result = DB::select(
"SELECT *
FROM orders
JOIN restaurants ON orders.restauant_id = restaurants.id
WHERE orders.status = 'complete' :restaurant_sql AND
orders.created_at >= :start_date",
["restaurant_sql" => $restaurantSql, "start_date" => $startDate]
);
The start_date
works as per the documentation from Laravel but the restaurant_sql
is not working. Any idea how I can achieve this?
Upvotes: 0
Views: 1109
Reputation: 737
I think your problem is here
$result = DB::select(
"SELECT *
FROM orders
JOIN restaurants ON orders.restauant_id = restaurants.id
WHERE orders.status = 'complete'". $restaurantSql. "AND
orders.created_at >= :start_date",
["restaurant_sql" => $restaurantSql, "start_date" => $startDate]
);
Upvotes: 1