在Laravel 4中按数值SQL查询排序

时间:2013-12-11 13:20:35

标签: php sql laravel

我正在展示我博客评分最高的文章:

$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, ))

1 个答案:

答案 0 :(得分:1)

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