Order by the difference of two columns in Laravel 5.3 - php

I have an eloquent query where one of the orderBy is the difference of two columns.
$mymodel = Level::where([['ColA', 5], ['ColB', 10], ['ColC', 7]])
->orderBy('ColA', 'Desc')
->orderBy('ColA' - 'ColB', 'Desc')
->orderBy('ColC', 'Desc')
->orderBy('ColD', 'Asc')
->pluck('userId')->toArray();
The exact same code on localhost with sqlite works without an error. But on production with MySQL has the following error
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'order clause' (SQL: select `userId` from `levels` where (`ColA` = 5 and `ColB` = 10 and `ColC` = 7) order by `ColA` desc, `0` desc, `ColC` desc, `ColD` asc)

$model = Level::where($wheres)
->orderByRaw('(ColA - ColB) DESC')
->pluck('userId')
->toArray();

Related

Error in Laravel pagination with complex select statement

I have the problem with pagination in laravel framework.
I built my query in this way:
$auctions = Auction::where('status', '=', 1)
->Where('minQuantity', '>', 0)
->whereRaw('endTime > NOW()');
$auctions->selectRaw('*,' . DB::raw('IF ((SELECT COUNT(*) FROM observed_auctions WHERE observed_auctions.idUser=' . intval($userId) . ' AND observed_auctions.idAuction=auctions.id)>0,\'true\',\'false\') as isObserved'));
Next, I get the result:
$auctions->paginate(15, ['name'], 'page', $currentPage);
It works pretty well until I want to find only observed auctions if I added where clause:
$auctions->where('isObserved', '=', true);
I get error:
Column not found: 1054 Unknown column 'isObserved' in 'where clause' (SQL: select count(*) as aggregate from auctions where status = 1 and minQuantity > 0 and endTime > NOW() and isObserved = 1)
How can I solve this problem?

YEAR(begin_date) unknown column in laravel

SELECT COUNT(*) as count, MONTH(begin_date)
FROM `events`
WHERE (YEAR(begin_date) = YEAR(CURDATE()))
OR (YEAR(begin_date) = YEAR(CURDATE()) + 1)
GROUP BY MONTH(begin_date)
Here is sql query, i want to write it in laravel eloquent.
what i try:
$oncoming_events = DB::table('events')
->select(DB::raw('count(*) as numOfOncomingEvents, MONTH(begin_date)'))
->where('YEAR(begin_date)', '=', 'YEAR(CURDATE())')
->orWhere('YEAR(begin_date)', '=', 'YEAR(CURDATE()) +1')
->groupBy('MONTH(begin_date)')->get();
Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'YEAR(begin_date)' in 'where clause' (SQL: select count(*) as numOfOncomingEvents, MONTH(begin_date) from events where YEAR(begin_date) =
laravel 5.6
btw
sql query works..
You need to use DB::raw() in where to tell the query builder that it is not column name it is data manipulation in query,
$oncoming_events = DB::table('events')->select(DB::raw('count(*) as numOfOncomingEvents, MONTH(begin_date)'))->where(DB::raw('YEAR(begin_date)'), '=', 'YEAR(CURDATE())')->orWhere(DB::raw('YEAR(begin_date)'), '=', 'YEAR(CURDATE()) +1')->groupBy(DB::raw('MONTH(begin_date)'))->get();

How to write mysql query in laravel 5.4?

I am new to laravel and i want to write mysql query in laravel 5.4.
query is like :
note: avoid column names..
SELECT *
FROM (SELECT DISTINCT *
FROM messages
WHERE (from_id=1 OR to_id=1)
ORDER BY created DESC) as m
GROUP BY `from_id`
I tried but gives error.
$messages = DB::table('messagetbl')
->select('*')
->Where(function($query) use ($userid){
$query->distinct()
->where('senderid',$userid)
->orWhere('receiverid',$userid)
->orderBy('datetime','desc');
})
->groupBy('senderid')
->get();
Error:
SQLSTATE[42000]: Syntax error or access violation: 1055
Expression #1 of SELECT list is not in GROUP BY clause and contains
nonaggregated column 'db.messagetbl.id' which is not functionally
dependent on columns in GROUP BY clause; this is incompatible with
sql_mode=only_full_group_by (SQL: select * from messagetbl where
(senderid = 8 or receiverid = 8) group by senderid)
Thanks in advance.
I believe something like this:
DB::table('messages')
->select('*')
->where('form_id', '=', 1)
->orWhere('to_id', '=', 1)
->orderBy('created', 'desc')
->groupBy('form_id')
->distinct()
->get();

Comparing timestamps from two different tables in Laravel 5

I am trying to get results out of union by showing only results that were updated after I last checked (defined by $last_check)
$last_check = CheckNotifications::where('notif_check_user_id', '=', $user_id)->pluck('updated_at');
$get_projects = DB::table('requests')
->join('notifications', 'notifications.notif_project_id', '=', 'requests.id')
->select(DB::raw('requests.updated_at, requests.request_name, "" as fullname, "P" as flag'))
->where('notif_user_id', '=', $user_id)
->whereRaw('requests.updated_at > requests.created_at');
$comments = DB::table('project_comments')
->leftJoin('users', 'comment_user_id', '=', 'users.id')
->leftJoin('requests', 'comment_project_id', '=', 'requests.id')
->select(DB::raw('project_comments.updated_at, requests.request_name, users.fullname, "C" as flag'));
$get_notifications = $get_projects->union($comments)
->whereRaw('updated_at > $last_check')
->orderBy('updated_at', 'desc')
->get();
The union works just fine until I add that last whereRaw statement. With the statement added, I get a SQL Syntax/Access error (#42000). I think it has something todo with the plucking of updated_at for the comparison. Any ideas? Thanks in advance!
Edit: Here's the error code
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '15:09:06) union (select project_comments.updated_at, requests.id as request_id, ' at line 1 (SQL: (select requests.updated_at, requests.id as request_id, requests.request_name, "" as fullname, "P" as flag from `requests` inner join `notifications` on `notifications`.`notif_project_id` = `requests`.`id` where `notif_user_id` = 1 and requests.updated_at > requests.created_at and requests.updated_at > 2015-07-29 15:09:06) union (select project_comments.updated_at, requests.id as request_id, requests.request_name, users.fullname, "C" as flag from `project_comments` left join `users` on `comment_user_id` = `users`.`id` left join `requests` on `comment_project_id` = `requests`.`id`) order by `updated_at` desc)
there whould be 2 updated_at column , Please attach your error while mentioning something like that again I can't be sure of the reason.
the solution is simply to write the table name before the column name
change
->whereRaw('updated_at > $last_check')
into
->whereRaw('requests.updated_at > $last_check')
and change orederby() to be after the whereRaw()
you had written the right code just few lines before :D
I hope this solve your problem
add that whereRaw clause for each of previous two queries
->where('requests.updated_at','>', $last_check)
or
->whereRaw('requests.updated_at > ?', [$last_check])
probably where is not available with union
just curious : if this is working?
$get_notifications = $get_projects->union($comments)
->where(function($query) use ($last_checked){
$query ->where('requests.updated_at','>', $last_check);
})
->orderBy('requests.updated_at', 'desc')
->get();

Laravel 3 - Order by the division of two fields

I need following SQL converted to eloquent
select * from medias order by likes/views DESC, views ASC
I need to use paginate on the result, that is why i prefer eloquent.
Some of my other SQL queries are
$media_list = Media::order_by('likes', 'desc')->paginate($per_page);
I tried
$media_list = Media::order_by('likes/views', 'desc')->paginate($per_page);
But it gives error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'likes/views' in 'order clause'
SQL: SELECT * FROM `medias` ORDER BY `likes/views` DESC LIMIT 20 OFFSET 0
Anyone know how to fix this ?
Try , instead of /
$media_list = Media::order_by('likes,views', 'desc')->paginate($per_page);
or
$media_list = Media::order_by('likes`,`views', 'desc')->paginate($per_page);
And also this is the standard way of doing in laravel
$media_list = Media::order_by('likes', 'desc')->orderBy('views', 'desc')->paginate($per_page);
$media_list = DB::table('medias')
->select(DB::raw('(likes/views) AS resultant'))
->order_by('resultant', 'desc')->orderBy('views', 'desc')
->get();

Categories