0

How can I return posts from two or more different authors using one single SQL query? Authors array is received from the database and is different for every single user (it depend on what author you are following).

I return $array variable with IDs of the authors.

$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;
}

How can I return all posts, posted by authors 15, 12, 18 using a single line or just returning to single-sql query and sort it by date?

I've tried to make different sql selects for every single creator and merge arrays, but then it's very hard to order

GMB
  • 216,147
  • 25
  • 84
  • 135
Adrijus Jakučionis
  • 265
  • 1
  • 3
  • 12

2 Answers2

3

Use whereIn, which is specifically built for your purpose:

$posts = DB::table('posts') 
    -> whereIn('author', $array) 
    -> orderBy('date', 'DESC') 
    -> get();
GMB
  • 216,147
  • 25
  • 84
  • 135
2

You need use whereIn instead of where:

->whereIn('author', $array)

Now your query looks like below:

$posts = DB::table('posts')->whereIn('author', $array)-> orderBy('date', 'DESC')->get();
GMB
  • 216,147
  • 25
  • 84
  • 135
Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49