SQL查询返回数据,其中从数组中选择作者

问题描述

如何使用一个SQL查询返回来自两个或更多不同作者的帖子?从数据库接收到authors数组,并且该数组对于每个用户都是不同的(取决于您关注的作者)。

我返回带有作者ID的$array变量。

$array = array(15,12,18); //this array is returned from database and is always different
$posts = DB::table('posts') -> where('author',$array]) -> orderBy('date','DESC') -> get();

foreach($posts as $post) {
  echo "Posted by " . $post->author;
}

我如何返回所有由作者15、12、18发表的帖子,使用单行显示,或者仅返回到单SQL查询并按日期排序?

我尝试为每个创建者创建不同的sql选择并合并数组,但是要订购非常困难

解决方法

使用whereIn,它是专门为您的目的而构建的:

$posts = DB::table('posts') 
    -> whereIn('author',$array) 
    -> orderBy('date','DESC') 
    -> get();
,

您需要使用whereIn而不是where

->whereIn('author',$array)

现在您的查询如下所示:

$posts = DB::table('posts')->whereIn('author',$array)-> orderBy('date','DESC')->get();