0

I've been trying to write a massive update query with a where clause, and I've found that Laravel 5.3 Eloquent Query Builder makes a syntax error.

The query is the following:

$query = $this->model
    ->where('state', "pending")
    ->whereRaw('created_at <= NOW() - INTERVAL 12 HOUR')
    ->update(['state' => "timeout"]);

Which is translated to this:

update `orders`
set `state` = timeout, `updated_at` = 2016-09-21 21:47:39
where `state` = pending and created_at <= NOW() - INTERVAL 12 HOUR

This query keeps failing since the values for the columns state and updated_at are not written with single quotes.

How can I force Laravel to write to put the single quotes correctly?

2 Answers 2

1

Maybe try where('created_at', DB::raw('NOW() - ..'));

And why are you putting peding in single quotes? Laravel escapes values automatically.

Sign up to request clarification or add additional context in comments.

5 Comments

I knew that I can use DB::raw, but I'd like to find a more... elegant solution, sort to speak. I'm using double quotes because the query builder is removing them too if I use single ones... Maybe this is related to the main problem? (Btw state is an enum)
Enum should not make a difference, because a string is sent to mysql anyway. I thinks that DB::raw would be a more elegant solution. If you start hacking like this, then I suggest just writing a raw query.
I'd rather use the Query Builder tools. I've edited the question to include the single quotes problem in the state column, I think they might be related
Ok, nevermind, this works, sorry for the inconvenience
@MārtiņšBriedis why not to use where('created_at', '<=', Carbon::now()->addHours(-12)) ?
0

Use something like

$results  = MyModel::where('user_id', Auth::user()->id)
            ->where('created_at','>=',\DB::raw('"'.$from.'"'))
            ->where('created_at','<=',\DB::raw('"'.$to.'"'))
            ->orderby('id','desc')
            ->paginate(15);

Hope this helps.

Comments

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.