[英]Get any of the item from the Array with whereIn in Laravel 5.3
I'm using laravel 5.3 and trying to build a query with multiple where and wherein function.我正在使用 laravel 5.3 并尝试使用多个 where 和 where 函数构建查询。 Here is my code:这是我的代码:
$posts_id = "1,3,4"; //from my query
$results = Post::select('*');
$results->whereIn('posts_id', [$posts_id]);
$resutls->get();
There is 1 post which have an id of 4 in my database, but my query doesn't returning anything.我的数据库中有 1 个帖子的 id 为 4,但我的查询没有返回任何内容。 Though there is 4 in my post ids $posts_id = "1,3,4";
虽然我的帖子 ID 中有 4 个$posts_id = "1,3,4";
. .
Need help, to get posts from any of the id, which I've included in my $posts_id
variable.需要帮助,从我包含在$posts_id
变量中的任何 id 获取帖子。
Thanks in Advance!提前致谢!
You need to pass an array to whereIn() method:您需要将数组传递给 whereIn() 方法:
$results = Post::whereIn('posts_id', explode(',' $posts_id))->get();
Note that you don't need to call each method in a separate line.请注意,您不需要在单独的行中调用每个方法。 You can chain them.你可以链接它们。 Also, the select('*') is not required.此外, select('*') 不是必需的。
You can create your array in any way you want, no need to use explode().你可以用任何你想要的方式创建你的数组,不需要使用explode()。
$ids = [1, 2, 3];
$results = Post::whereIn('posts_id', $ids)->get();
It may be good to check if the array isn't empty before making that query.在进行查询之前检查数组是否为空可能会很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.