【问题标题】:Laravel 4.2 check array is empty in whereIn clauseLaravel 4.2 检查数组在 whereIn 子句中为空
【发布时间】:2017-05-19 20:46:50
【问题描述】:

我使用elequent 进行查询我遇到whereIn 子句的问题,如果数组为空则不返回结果:

$idsUsers = empty(json_decode($data["idsUsers"])) ? null : json_decode($data["idsUsers"]);
$articles = DB::table('articles')
        ->whereIn('user_id',$idsUsers)
        ->orderBy('created_at','desc')
        ->paginate(10);

如何在 whereIn 方法中使用我的数组来检查它是否为空或 null

【问题讨论】:

  • Laravel 4 或 5.2,它们在查询方面有很多不同之处。
  • Laravel 4.2 ...

标签: laravel laravel-4 eloquent laravel-5.2


【解决方案1】:

尝试使用条件:

$articles = DB::table('articles')->orderBy('created_at','desc');

if (!empty($idsUsers)) {
    $articles = $articles->whereIn('user_id', $idsUsers);
}

$articles = $articles->paginate(10);

【讨论】:

  • 此查询返回 stdclass 的集合.. 我可以将该集合转换为 Article 对象吗?
  • 当然。只需将DB::table('articles')-> 替换为Article::
【解决方案2】:

你可以试试这个

$idsUsers = empty(json_decode($data["idsUsers"])) ? null : json_decode($data["idsUsers"]);

$articles = DB::table('articles')
              ->where(function($query) use ($idsUsers){
                if(count($idsUsers))
                {
                  $query->whereIn('user_id',$idsUsers);
                }
              })->orderBy('created_at','desc')->paginate(10);

希望这会有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-03
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多