php-laravel框架下,通过指定字段对结果集进行排序

1 $products = Blog::with('user')->where('user_status', 'normal')
2 ->whereIn('blogId', $blogId)
3 ->orderByRaw("FIELD(blogId, " . implode(", ", $blogId) . ")")
4 ->get();

通过laravel框架的预加载功能(with)查询Blog表,想要对查出的结果集进行排序,问题在于正常情况下,通过数据库中的某个字段进行asc或者desc排序,但是我想指定一个排序方法怎么办,这时就需要用到

->orderByRaw("FIELD(blogId, " . implode(", ", $blogId) . ")")

解释一下其中的参数

blogId是数据库中要排序的字段

$blogId = {

[10100326],

[10108965],

[10106639],

[10101123]

}

因为orderByRaw接收的参数是字符串,所以需要通过implode把数组转化为字符串。