I have a requirement to add multiple where clauses to a Laravel SQL query.
So far my PHP code has been:
date_default_timezone_set('America/Los_Angeles');
$today = getdate();
$year = $today['year'];
$month = $today['mon'];
$day = $today['mday'];
$today_ = $day.'-'.$month.'-'.$year;
$result = DB::table('task')
->select('*')
->where(
['rowstate', '<>', 'Ready'],
['DATE_FORMAT(due_date, "%d-%m-%y")', '<', $today_])
->get();
But above code returns:
Column not found: 1054 Unknown column '0' in 'where clause'
(SQL: select * from `task_tab` where (`0` = rowstate and `1` = <> and `2` = Ready))
I want to generate below SQl statement:
SELET *
FROM task
WHERE rowstate <> 'Ready'
AND DATE_FORMAT(due_date, "%d-%m-%y") < $today
You have 2 possible solutions.
Instead of:
->where(['rowstate', '<>', 'Ready'], ['DATE_FORMAT(due_date, "%d-%m-%y")', '<', $today_])
you can use
->where('rowstate','<>','Ready')->where(DB::raw('DATE_FORMAT(due_date, "%d-%m-%y"','<', $today_);
or
you can use array syntax like this:
->where([
['rowstate', '<>', 'Ready'],
[DB::raw('DATE_FORMAT(due_date, "%d-%m-%y")'), '<', $today_]
]);
So to sum up you were missing enclosing your data into outer array, and you need to use DB::raw in case you don't use raw column names
You can't use sql function's directly in laravel where class. You need to use DB::raw() for same.
So your query will be like :
$result = DB::table('task')
->select('*')
->where('rowstate', '<>', 'Ready')
->where(DB::raw('DATE_FORMAT(due_date, "%d-%m-%y")'), '<', $today_)
->get();
Try this
->where([
// ^
['rowstate', '<>', 'Ready'],
['DATE_FORMAT(due_date, "%d-%m-%y")', '<', $today_]])
// ^
Related
Im having a hard time converting this raw MySQL query in phpmyadmin. I want to convert it to laravel's query builder or eloquent. I already configured the relationships in the model. Can someone convert my query to querybuilder and eloquent? I tried some converter but it doesnt work for me. Thanks
Raw Query
SELECT count( * ) FROM users u, sectionschedules s, notes n
WHERE u.parent_id=26
AND u.section_id=s.section_id
AND s.id = n.schedule_id;
Query I tried
$notes = DB::table('notes')
->join('users', 'users.section_id', '=', 'notes.section_id')
->join('sections','sections.section_id', '=', 'sectionschedules.section_id')
->join('sectionschedules', 'sectionschedules.id','=','notes.schedule_id')
->where('user.parent_id', '=', 26)
->count();
Error I got
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user.parent_id' in 'where clause
Try
$notes = DB::table('sectionschedules')
->select('notes.*','sectionschedules.*','users.*')
->join('users','users.section_id', '=', 'sectionschedules.section_id')
->join('notes', 'sectionschedules.id','=','notes.schedule_id')
->where('users.parent_id', '=', 26)
->count();
$notes = DB::table('notes')
->join('users', 'users.section_id', '=', 'notes.section_id')
->join('sections','sections.section_id', '=', 'sectionschedules.section_id')
->join('sectionschedules', 'sectionschedules.id','=','notes.schedule_id')
->where('users.parent_id', '=', 26)
->count();
Users.parent id as defined not user.parent_id
I'm constructing a RAW database query with Laravel (5.4) and I'm getting a problem in that laravel is placing quotes in the SQL output for a variable within a join... The result is that mysql thinks that the variable... Which for example would output to 1 or something numeric is a column and outputs error "Cannot find column '1' in ON clause
PROBLEM SQL CLAUSE:
->join('event_jury_sub_detail', function($join) use($userid)
{
$join->on('event_jury_sub_detail.evtpartsub_id', '=', 'event_partsubmissions.id')
->on('event_jury_sub_detail.authoruser_id','=',$userid);
Problem: $userid gets quotes... And becomes "and event_jury_sub_detail.authoruser_id = 1" - Laravel treats it as a column to look up and fails.
If the quotes are removed it works fine... How to resolve this?
FULL QUERY
$tbl_return = DB::table('event_partsubmissions')
->select(DB::raw('event_partsubmissions.*,
users.usr_firstnames,
users.usr_surnames,
users.email,
users.usr_nationality,
users.usr_country,
event_jury_sub_detail.id as evtjurysubdetid,
event_jury_sub_detail.evtjurysubdet_pointsawarded,
event_jury_sub_detail.evtjurysubdet_notes,
event_jury_sub_detail.evtjurysubdet_randomkey
'))
->join('event_participation', 'event_partsubmissions.evtpartsub_evtpartid', '=', 'event_participation.id')
->join('users', 'evtpart_userid', '=', 'users.id')
->join('event_jury_sub_detail', function($join) use($userid)
{
$join->on('event_jury_sub_detail.evtpartsub_id', '=', 'event_partsubmissions.id')
->on('event_jury_sub_detail.authoruser_id','=',$userid);
})
->where('event_partsubmissions.evtpartsub_evtid', '=', $id)
->where('event_partsubmissions.evtpartsub_enabled', '>=', $partlevel)
->where('event_participation.evtpart_enabled', '>=', 1)
->where('event_participation.evtpart_level', '>=', 100)
->where('users.usr_enabled', '>=', 1)
->get();
You can try to use the alias for table joins:
->join('event_jury_sub_detail as ejsd', ...
And use the alias in following places:
->$join->on('ejsd.evtpartsub_id', '=', 'event_partsubmissions.id')
For scalar params in join conditions, you can use DB wrapper like DB::raw($userid):
->on('ejsd.authoruser_id','=',DB::raw($userid));
use DB::raw()
->on(DB::raw("event_jury_sub_detail.authoruser_id = '".$userid."'"))
I want to convert this query into laravel eloquent,
select * from schedule where (now() between start_date and end_date);
I tried using whereBetween, but I got some error.
$schedule = Schedule::whereBetween(Carbon::now(), ['start_date', 'end_date'])->get();
the error looks like this
QueryException in Connection.php line 647:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '2017-06-01 06:17:30' in 'where clause' (SQL: select * from schedule where 2017-06-01 06:17:30 between start_date and end_date)
any idea?
$from = $request->from;
$to = $request->to;
$title="Sales From: ".$from." To: ".$to;
$sales = Sale::whereBetween('created_at', [$from.' 00:00:00',$to.' 23:59:59'])->get();
$schedule = Schedule::where('start_date', '<=', Carbon::now())
->where('end_date', '>=', Carbon::now())
->get();
Or
$schedule = Schedule::whereRaw('(now() between start_date and end_date)')->get();
The whereBetween is used only when you want to find a row where a single column is between 2 values, what you want to do is :
$now = Carbon::now();
$schedule = Schedule::where('start_date', '<=', $now)
->where('end_date', '>=', $now)
->get();
whereBetween should used like this, ->whereBetween('loc_lng', array(-0.24272918701172, -0.24272918701172)) whose first parameter is the column name, and the second is the region.
In you situation you can use ->where('start_date', '<' Carbon::now())->where('end_date', '>' Carbon::now());
You can use whereBetween('date_field',[$from_date, $to_date]) to fetch the data between two dates but it should be in the array format.
$products = Sale::with('products')
->whereBetween('date',[$from_date, $to_date])
->get();
return response()->json($products);
You can also use whereBetween(whereBetween('date_field',[$from_date, $to_date])) with multiple where conditions like:
$products = Sale::with('products')
->whereBetween('date',[$from_date, $to_date])
->where(function ($query) use ($search) {
$query->where('employee_id', 'like', '%'.$search.'%')
->orWhere('employee_name', 'like', '%'.$search.'%');
})
->get();
return response()->json($products);
I hope this will work for you :)
I want to sort my Laravel query builder results on a custom column (concat of first_name and last_name).
What I have done is-
$summary = DB::table('service_rating')
->join('partners', 'partners.id', '=', 'service_rating.partner_id')
->join('users', 'users.id', '=', 'partners.user_id')
->select(
DB::raw("CONCAT( users.first_name,' ', users.last_name) as lawn_pro"),
DB::raw ('AVG(service_rating.rating) as rating'),
DB::raw ('COUNT(service_rating.rating) as jobs'),
DB::raw ('SUM(service_rating.rating) as payout')
)
->where('customer_id', '=', Auth::user()->id)
->whereRaw('service_rating.created_at >= DATE(NOW()) - INTERVAL '.$no_of_day_to_show.' DAY')
->groupBy('service_rating.partner_id')
->orderBy('lawn_pro', 'asc');
So, I am getting error for this line -
->orderBy('lawn_pro', 'asc');
And error is like this-
Can anyone please help ?
Apparently you are using the count() function on your query, this ignores the select attributes because we only want to know the count of the rows. Because of this, lawn_pro is not available in the query.
I would suggest to execute the query and then count the available rows.
$rows = $summary->get();
$count = count($rows);
I'm trying to order my query by hour, but I don't know how to do it. In MySql will be:
ORDER BY HOUR(FechaTermino) // FechaTermino = Timestamp... (dd/mm/yy hh:mm:ss)
but in laravel??
this is my Query Builder
$servicios = DB::table('Servicio_Tecnico')
->join('Servicio', 'Servicio_Tecnico.Servicio_idServicio', '=', 'Servicio.idServicio')
->join('Tecnico', 'Servicio_Tecnico.Tecnico_idTecnico', '=', 'Tecnico.idTecnico')
->whereRaw('DAY(Servicio.FechaTermino) = ?', array($dia))
->where('Servicio.Completado', '=', '1')
->orderBy('FechaTermino', 'Desc')
->paginate(10);
Just use a raw query:
->orderBy(DB::raw('HOUR(FechaTermino)'))
Check this answer, very similar.