Version
Laravel : 7.28.3
mysql : Ver 14.14 Distrib 5.7.29, for osx10.15 (x86_64) using EditLine wrapper
Tables
- contents (id)
- content_views (id, content_id)
What I'm Trying To Do
I would like to get a rank of a content by how many it has content_views.
Code
App/Models/Content.php
/**
* Attribute of get rank by views
*
* @return Int
*/
public function getViewsRankingAttribute()
{
DB::statement(DB::raw('set @c=0'));
$result = collect(
DB::select('select rank from
(
select _ranking.*, @c:=@c+1 as rank from
(
select content_views.content_id, count(content_views.id) as views
from content_views
group by content_views.content_id
order by views desc
) as _ranking
) as ranking
where content_id = :contentId', [
'contentId' => $this->id
]))
->first();
return $result ? $result->rank : '-';
}
This is actually working in mysql 5.8 but it's not in 8.0.
Error
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 'from ( select _ranking., @c:=@c+1 as rank from ' at line 1 (SQL: select rank from ( select _ranking., @c:=@c+1 as rank from ( select content_views.content_id, count(content_views.id) as views from content_views group by content_views.content_id order by views desc ) as _ranking ) as ranking where content_id = :contentId)