简体   繁体   English

在 WhereIn 中传递数组并按相同数组排序结果

[英]Pass array in WhereIn and Order results by same array

I'm trying to pass an array of lists of post_id from post_views table to posts table.我正在尝试将一系列 post_id 列表从 post_views 表传递到 posts 表。 What I got so far is, when I pass the $newsTagRetreived array to $posts, it only gives me first posts.到目前为止我得到的是,当我将 $newsTagRetreived 数组传递给 $posts 时,它只给我第一篇文章。 Current code looks like this:当前代码如下所示:

$newsTagRetreived = NewsTag::where('created_at', '>', 
                            \Carbon\Carbon::now()->subDay()->toDateTimeString())
                            ->orderBy('views','desc')
                            ->pluck('post_id')
                            ->implode(', ');
// dd($newsTagRetreived); 

this returns me exactly all lists of posts_id I need in exact order I need but only 1 post.这将按照我需要的确切顺序返回我需要的所有posts_id列表,但只有1个帖子。

In the post,在文中,

$posts = Post::where('post_status', 'publish')
->where('post_type', 'post')->whereIn('ID',[$newsTagRetreived])->paginate('12');

How do I get all posts in the same order as passed by $newsTagRetreived in $posts?如何以与 $posts 中 $newsTagReretived 传递的顺序相同的顺序获取所有帖子? Thank you!谢谢!

//...
->orderByRaw(\DB::raw("FIELD(ID, ". implode(",",$newsTagRetreived) ." )"))->paginate('12');
//...

See http://oldblog.codebyjeff.com/blog/2015/02/laravel-quick-tip-order-by-rawhttp://oldblog.codebyjeff.com/blog/2015/02/laravel-quick-tip-order-by-raw

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM