我有以下SQL查询:
SELECT * from db.tableA WHERE field in (SELECT id FROM db.tableB where other_field = value);
我想从tableA中选择哪个字段位于子查询返回的值数组中。问题是:如何以雄辩的方式做到这一点? 我目前的解决方案(我认为非常难看)如下:
$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();
有更好的方法吗?
谢谢!
答案 0 :(得分:1)
一个查询比两个查询更好!
因此,下面使用eloquent执行 whereIn 子句中具有子查询的查询:
\App\tableA::whereIn("field", function ($query) use ($value) {
$query->select('id')
->from('table_b')
->where('other_field', $value);
})->get()
答案 1 :(得分:0)
让我们将代码简化为。
$arr = \App\tableB::where("other_field", "=", $value)->lists('id')->all();
$res = \App\tableA::whereIn("field", $arr)->get();
与all()链接的lists()会自动将您的集合转换为数组。但是在laravel 5.0或更低版本中,你不需要使用all()将你的集合转换为数组。