【问题标题】:Get any of the item from the Array with whereIn in Laravel 5.3在 Laravel 5.3 中使用 whereIn 从数组中获取任何项目
【发布时间】:2017-10-04 22:53:50
【问题描述】:

我正在使用 laravel 5.3 并尝试构建具有多个 where 和 where 函数的查询。这是我的代码:

$posts_id = "1,3,4";  //from my query
$results = Post::select('*');   
$results->whereIn('posts_id', [$posts_id]);
$resutls->get();

我的数据库中有 1 个 id 为 4 的帖子,但我的查询没有返回任何内容。虽然我的帖子中有 4 个 ID $posts_id = "1,3,4";

需要帮助,从我的 $posts_id 变量中包含的任何 id 获取帖子。

提前致谢!

【问题讨论】:

    标签: php laravel-5 laravel-eloquent where-in laravel-query-builder


    【解决方案1】:

    您需要将一个数组传递给 whereIn() 方法:

    $results = Post::whereIn('posts_id', explode(',' $posts_id))->get();
    

    请注意,您不需要在单独的行中调用每个方法。你可以把它们串起来。此外,不需要 select('*')。

    你可以用任何你想要的方式创建你的数组,不需要使用explode()。

    $ids = [1, 2, 3];
    $results = Post::whereIn('posts_id', $ids)->get();
    

    在进行查询之前检查数组是否为空可能会很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      相关资源
      最近更新 更多