Reputation: 405
Here is the original code:
$invoice = DB::select('SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "' . company()->id . '" ');
return $invoice[0]->invoice_number;
The above works great, but I want to use it like this:
$invoice = DB::select('SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "' . company()->id . '" where depa_series = "2" ');
return $invoice[0]->invoice_number;
But this gives the following error:
Illuminate\Database\QueryException
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax
to use near ' where depa_series = "2"' at line 1 (SQL: SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "140", where depa_series = "2" )
How to use multiple WHERE clauses in DB::select
?
Thank you!
Upvotes: 0
Views: 97
Reputation: 51
here is what you should do $invoice =
DB::table('invoices') ->selectRaw('MAX(CAST(invoice_number as UNSIGNED)) as invoice_number') ->where(['company_id', company()->id, 'depa_series', "2"]) ->get(); return $invoice[0]->invoice_number;
There will no need to using multiple where statements. You can just put all in an array.
Upvotes: 0
Reputation: 7972
Have a look at the selectRaw
method
$invoice = DB::table('invoices')
->selectRaw('MAX(CAST(invoice_number as UNSIGNED)) as invoice_number')
->where('company_id', company()->id)
->where('depa_series', "2")
->get();
return $invoice[0]->invoice_number;
Upvotes: 3
Reputation: 8699
The query gives a syntax error, because you use where
twice.
Try to change it to this, by using the AND
condition:
DB::select('SELECT MAX(CAST(`invoice_number` as UNSIGNED)) as invoice_number FROM `invoices` where company_id = "' . company()->id . '" AND depa_series = "2"');
Upvotes: 3