I'm very new to Laravel and don't quite understand the DB::table
method in conjuction with an AND
clause.
So I have this query at the moment:
$query = DB::select( DB::raw("SELECT * FROM tablethis WHERE id = '$result' AND type = 'like' ORDER BY 'created_at' ASC"));
It is working, but I'd like to use Laravel's Query Builder to produce something like:
$query = DB::table('tablethis')->where('id', '=', $result)->where('type', '=', 'like')->orderBy('created_at', 'desc')
But this seems to ignore the second where()
completely. So, basically how do I make this work?
Just adding another ->where
behind another ->where
is the way to get another where
statement
So your code should be fine.
$query = DB::table('tablethis')->where('id', '=', $result)->where('type', '=', 'like')->orderBy('created_at', 'desc')
There must be something wrong with a different part. I do hope this isn't your full query.
If it is, you need a ->get()
at the end.
For sure this code should work as expected.
I don't know how you check the query executed, but you can go to app/providers/EventServiceProvider.php
(I assume you have L5) and in boot
method add:
Event::listen(
'illuminate.query',
function ($sql, $bindings, $time) {
$sql = str_replace(array('%', '?'), array('%%', "'%s'"),
$sql);
$full_sql = vsprintf($sql, $bindings);
file_put_contents(storage_path() . DIRECTORY_SEPARATOR .
'logs' . DIRECTORY_SEPARATOR . 'sql_log.sql',
$full_sql . ";
", FILE_APPEND);
}
);
to see exact SQL that was executed.
In addition (but it's just improvement) when using =
operator, you can omit it, so you can use here:
$query = DB::table('tablethis')->where('id', $result)->where('type', 'like')->orderBy('created_at', 'desc');