Invalid parameter number on Laravel subquery - laravel

When I run the below query I get the following error: Invalid parameter number: mixed named and positional parameters.
$subQuery = DB::table('earliest_count')
->select('reporting_week')
->where('vendor_name', $vendorName);
$dates = DB::table('invoice')
->select('week_beginning_date', 'week_end_date')
->whereRaw(':sql BETWEEN `week_beginning_date` AND `week_end_date`', [':sql' => DB::raw("({$subQuery->toSql()})")])
->where('week_beginning_date', '<', $date)
->orderBy('week_beginning_date')
->limit(1)
->mergeBindings($subQuery)
->get();
If I replace the whereRaw with the following it works:
->whereRaw('(SELECT reporting_week FROM earliest_count WHERE vendor_name = "My Vendor") BETWEEN `week_beginning_date` AND `week_end_date`')
How can I get the subquery to work without having to write the exact query as a string?
Edit
I did try the following, and I get no errors but I don't get any results. (When I enter the subquery as a string I do get a result):
->whereRaw('? BETWEEN `week_beginning_date` AND `week_end_date`', [DB::raw("({$subQuery->toSql()})")])

Laravel doesn't use named placeholders, you should use ? for placeholders and remove the name from the parameters array.
Like this:
->whereRaw('? BETWEEN `week_beginning_date` AND `week_end_date`', [DB::raw("({$subQuery->toSql()})"])

Related

get Field name from the query builder result

I need to get field names from the query builder result.
For a single table
I could use
DB::getSchemaBuilder()->getColumnListing('table_name');
but what i need is from the query builder result.
DB::table('users as a')
->leftJoin('userwork AS uk','uk.WORK_ID', '=','a.WORK_ID')
->selectRaw("a. name ,uk.work_name as work ,concat('+',uk.work_phone) as phone")
->get();
I want to extract the attribute name to get the result like below
['name','work','phone'];
I end up using array_keys method after converting the first result of the query builder to array.
$db_fields=array_keys((array)$items->first());
Do you need like this?
DB::table('users as a')
->leftJoin('userwork AS uk','uk.WORK_ID', '=','a.WORK_ID')
->select("a. name ,uk.work_name as work ,concat('+',uk.work_phone) as phone")
->get();
just using select. You could write on your controller.

Laravel - WhereExists returning "Invalid parameter number: parameter was not defined"

I'm trying to use whereExists() on an existing Eloquent query builder (called $trips):
$trips = $trips->whereExists(function ($query) use ($filterValue) {
$query->from(DB::raw("jsonb_array_elements(passengers->'adults'->'persons') as p(person)"))
->whereRaw("p.person->>'name' LIKE '?%'", $filterValue);
});
The query I'm trying to create in raw postgres format is the following (this query works fine using pgAdmin):
SELECT *
from trips
WHERE exists (select *
from jsonb_array_elements(passengers -> 'adults' -> 'persons') as p(person)
where p.person ->> 'name' LIKE 'Prof%');
And I'm receiving this error:
Invalid parameter number: parameter was not defined
I think the problem is small, but I can't see it myself.
The parameter definition in your whereRaw() statement is not quite correct. Parameterized queries are not just string replacements. Your query as written doesn't have a parameter in it, it has a string literal of '?%'. You need to change this to a query parameter, and append the % wildcard to the string you pass in.
Try this:
->whereRaw("p.person->>'name' LIKE ?", $filterValue.'%')

Query using eloquent whereMonth where date is string

In one of the tables a column with type of varchar contains a date with the following format day-month-year. I would like to run a query using eloquent on that table with whereYear and whereMonth, but I get an error since the column booking_date is not of type Date.
The query I am trying to run is
MyTable::whereYear('booking_date', '=', $year)
->whereMonth('booking_date', '=', $month)
->get();
And getting the following error
"SQLSTATE[42883]: Undefined function: 7 ERROR: function pg_catalog.date_part(unknown, character varying) does not exist\nLINE 1: ...\" = $1 and \"said_table\".\"deleted_at\" is null) and extract(ye...\n ^\nHINT: No function matches the given name and argument types. You might need to add explicit type casts.
Is there a way to cast the string value to a date before querying it, maybe with using raw expressions? If yes, any hints would be great.
If this field is going to be a date on the particular model all the time (and with a name like 'booking_date', it might well be), it is even easier than having to deal with it on every query. You can cast it within the dates field on the model itself:
protected $dates = [
'booking_date',
];
By default, Eloquent will convert the created_at and updated_at columns to instances of Carbon, and the above will do the same for booking_date. No further casting required. From Laravel docs on date mutators
You may easily achieve that thanks to Carbon library which is included within Laravel:
use Carbon\Carbon;
$targetDate = Carbon::now()->year($year)->month($month);
MyTable::whereYear('booking_date', '=', $targetDate)
->whereMonth('booking_date', '=', $targetDate)
->get();

Laravel i will get integer in DB query

after returning $query from this:
$query = DB::table('pets')->select('id')->where('id', '=', $pet->id)->where('user_id', '=', Auth::id())->get();
for example i get this result : [{"id":"66"}]
how can i get only 66 as integer?
Thanks!
Instead of get() which returns the entire collection of selected data, use value('id') to get the first value of the id field. You also wouldn't need select('id') if you use this method.

Eloquent select where($value) issues

I am trying make select in eloquent:
$query = $query->where($value);
echo $value is:
´column´, ´<´, ´3´
BUT i have error: Unknown column ''column', '=', '3'' in... (look at quotation mark). If i write directly:
$query->where( ´column´, ´<´, ´3´);
Everything is okay
where() wants at least two arguments, but for the way you're using it it will need three. where('column', '<', $value) where $value is 3.
References:
http://laravel.com/docs/queries#advanced-wheres
http://laravel.com/api/source-class-Illuminate.Database.Query.Builder.html#268-324
$user = DB::table('users')->where('name', 'John')->first();
$users = DB::table('users')->where('votes', '>', 100)->get();
Where() required at least two parameters but it will accept three parameters.
Two parameters are compulsory:
table column name
compare value
in your example, you have only passed one parameter and will be consider as a table column name. obviously it will not match with the column name.
However, if you provide 3 parameters, ensure that you place the value parameter as 3rd parameter.
More:
http://laravel.com/docs/queries#selects

Resources