根据Laravel中的几个值对字段排序

时间:2018-12-16 08:03:34

标签: laravel laravel-5

我有一系列城市代码

$cities=[9,12,14,2,3,4,5,6,8,10,11,13]

我的帖子表有一个名为city_id的外键

我想根据此数组的值对帖子进行排序

以这种方式:要加载的城市9的第一个帖子,然后是城市12的帖子,然后是要加载的城市14的帖子等等

我尝试使用此方法,但这是错误的

$posts->orderByRaw('city_id in ? desc',$cities);

您能帮我找到最佳解决方案吗?

4 个答案:

答案 0 :(得分:0)

我想做这样的事情的唯一方法(至少现在是这样)

$all_posts = [];
$cities=[9,12,14,2,3,4,5,6,8,10,11,13];

foreach ($cities as city) {
    $city_posts = Post::whereRaw('city_id = ?', $city)->orderByRaw('created_at DESC');
    array_push($all_posts, $city_posts);
}

dd($all_posts);

答案 1 :(得分:0)

首先找到与posts相关的所有cities,然后按给定的顺序sort

$cities = [9,12,14,2,3,4,5,6,8,10,11,13]; // order you'd like to see with posts

$posts = Post::whereIn('city_id', $cities)->sort(function($a, $b) uses ($cities) {
    $pos_a = array_search($a->getAttributes()['city_id'], $cities);
    $pos_b = array_search($b->getAttributes()['city_id'], $cities);
    return $pos_a - $pos_b;
})->get();

// $posts contains the required order with city_ids

答案 2 :(得分:0)

您可以将原始查询与“ CASE something THEN index”一起使用,以这种方式告诉查询将某些内容视为索引,以便可以将0分配给数组的第一项。

$sql .= "....";

foreach($cities as $index => $city) {
    $sql .= "CASE {$city} THEN {$index}";
}

$sql .= "....";

答案 3 :(得分:0)

感谢朋友的解决方案,我使用了这种方法,我认为它比建议的朋友方法要简单

 $posts=$posts->orderByRaw('FIELD(city_id, '.$cities->implode( ', ').') asc')->orderBy('created_at','desc')->get();