【问题标题】:SQL query return data where author is selected from array [duplicate]SQL查询返回从数组中选择作者的数据[重复]
【发布时间】:2020-12-15 14:10:52
【问题描述】:

如何使用一个 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 选择,但是很难订购

【问题讨论】:

    标签: php mysql arrays laravel where-clause


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您需要使用whereIn 而不是where

      ->whereIn('author', $array)
      

      现在您的查询如下所示:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多