Laravel Eloquent ORM WHERE IN(子查询)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35724771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent ORM WHERE IN (subquery)
提问by Blackecho
I've the following SQL query:
我有以下 SQL 查询:
SELECT * from db.tableA WHERE field in (SELECT id FROM db.tableB where other_field = value);
I want to select from tableA where field is in the array of values returned by the subquery. The question is: how can I do this with eloquent? My current solution (which is very ugly I think) is the following:
我想从 tableA 中选择,其中字段位于子查询返回的值数组中。问题是:我怎样才能用 eloquent 做到这一点?我目前的解决方案(我认为这很丑陋)如下:
$a = \App\tableB::where("other_field", "=", $value)->select('id')->get();
$arr = array();
for ($i = 0; $i < count($a); $i++) array_push($arr, $a[$i]['id']);
$res = \App\tableA::whereIn("field", $arr)->get();
There is a better way of doing this?
有没有更好的方法来做到这一点?
Thanks!
谢谢!
采纳答案by oseintow
Lets simplify your code to.
让我们简化您的代码。
$arr = \App\tableB::where("other_field", "=", $value)->lists('id')->all();
$res = \App\tableA::whereIn("field", $arr)->get();
The lists() chained with all() will automatically convert your collection to an array. But wit laravel 5.0 or less you dont need the all() to convert your collection to an array.
与 all() 链接的 list() 将自动将您的集合转换为数组。但是在 laravel 5.0 或更低版本中,您不需要 all() 将您的集合转换为数组。
回答by Morteza Rajabi
One query is better than two queries!
一个查询胜过两个查询!
So the following performs a query having a subquery in whereInclause using eloquent:
因此,以下使用 eloquent在whereIn子句中执行具有子查询的查询:
\App\tableA::whereIn("field", function ($query) use ($value) {
$query->select('id')
->from('table_b')
->where('other_field', $value);
})->get()