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.
Related
I have a question. If created_at in my database is datetime and I want to make a query like this
whereDate('created_at', '=', date('Y-m-d'))
I get nothing as a result. How can i handle this situation ?
Another case: I want
whereDate('created_at', '=', date('M'))
You can use other helper functions maybe:
$query->whereYear('created_at', '=', date('Y'))
->whereMonth('created_at', '=', date('m'))
->whereDay('created_at', '=', date('d'));
Assuming you are using MySQL, you could use whereRaw:
whereRaw('created_at = CURDATE()')
For your second case:
whereRaw("month_name = DATE_FORMAT(CURDATE(), '%b')")
First Query: You can use Carbon specifying date format (date without time toDateString() / date with time toDateTimeString() ).
$query->whereDate('created_at', '=', Carbon::today()->toDateTimeString());
Second Query: Just query on whereMonth
$query->whereMonth('created_at', '=', date('m'));
I have this SQL query:
SELECT *, count(*) as mostView FROM users RIGHT JOIN visitors ON users.id = visitors.user_id GROUP BY users.id HAVING users.isActive=1 AND users.fullName IS NOT NULL AND users.photo_id IS NOT NULL AND users.role_id IN(1, 3) ORDER BY mostView DESC LIMIT 5
It works, but I need convert to Laravel eloquent, i'm using laravel 5.6, could any one helpe me thanks in advance
I'm assuming that you have map the relationship in your Model if you do you can do like below,
$userViews = User::->with('vistors')
->where('isActive',1)
->whereNotNull('fullName')
->whereNotNull('photo_id')
->whereIn('role_id ',[1,3])
->get();
$mostView = $userViews->sortBy(function ($collection) {
return $collection->vistors->count()
})->take(5)
hope this helps
Not going to spoon feeding but can provide you some ideas to convert raw sql to eloquent, your sql should ideally be like this:
User::selectRaw('*', 'count(*) as mostView')
->rightJoin()
->groupBy()
->having()
->where // whereNotNull // wherIn
->orderBy()
->take(5)
->get();
Kindly refer to laravel docs: https://laravel.com/docs/5.6/queries
Thanks for all i'm studies Database: Query Builder on the link
https://laravel.com/docs/5.6/queries
and so i solved my question by myself
the answer is:
$mostViews = DB::table('users')
->rightJoin('visitors', 'users.id' , '=' , 'visitors.user_id')
->select('users.*', DB::raw('count(*) as mostView'))
->where('isActive', '=', '1')
->whereNotNull('fullName')
->where('photo_id', '<>', 'NULL')
->where(function ($q){
$q->where('role_id', '=', '1')
->orWhere('role_id', '=', '3');
})
->groupBy('user_id')
->orderBy('mostView', 'desc')->take(5)->get();
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_]])
// ^
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 want to run this mysql query in Laravel 5 using the DB query :
// SELECT *, rating/number as total FROM `courses` order by total DESC;
This is what I tried :
$query = \DB::table('courses')->select('*');
$courses = $query->addSelect('rating/number as total')
->orderBY('total DESC')
->get();
but, rating/number is considered as a table column . The same thing happens when I tried it inside parenthesis (rating/number).
Any help?
$courses = \DB::table('courses')
->selectRaw('*, rating/number as total')
->orderBY('total', 'DESC')
->get();
Can you use Raw Expressions for it? Maybe something like this:
$courses = \DB::table('courses')
->select(DB::raw('*, (rating / number) as total'))
->orderBy('total DESC')
->get();