我正在展示我博客中评分最高的文章:
$top_articles = Post::orderBy('rating', 'DESC')->take(5)->get();
评级是从0到5,带小数(例如:3.8),所以我使用的是SQL列类型"float":
Column | Type | Attributs | Default
rating | float(2,1) | UNSIGNED | 3.0
我需要按评分订购文章,我想我应该使用"CAST":ORDER BY CAST(rating AS FLOAT)
但我不知道如何以雄辩的形式展示这一点:
Post::orderBy(DB::raw("'rating' AS DECIMAL(2,1)"), 'DESC')
正在引发以下错误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 'AS DECIMAL(2,1) desc limit 5' at line 1 (SQL: select * from `posts` order by 'rating' AS DECIMAL(2,1) desc limit 5) (Bindings: array ( 0 => 1, 1 => 2, 2 => 3, ))
CAST(expr AS type)
CAST()
函数接受任何类型的表达式,并生成指定类型的结果值
结果的类型可以是以下值之一:
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
参考编号:http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_cast