0

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?

1 Answer 1

1

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]
);
Sign up to request clarification or add additional context in comments.

3 Comments

I don't want to add the restaurant ids, I want to add the whole SQL dynamically.
Ok, I got it, I changed the code. please check it again
Didn't know it can work like that. Thank you sm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.