Laravel雄辩的ORM所在位置(子查询) [英] Laravel Eloquent ORM WHERE IN (subquery)

查看:518
本文介绍了Laravel雄辩的ORM所在位置(子查询)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下SQL查询:

SELECT * from db.tableA WHERE field in (SELECT id FROM db.tableB where other_field = value);

我想从tableA中进行选择,其中field在子查询返回的值数组中.问题是:我该如何雄辩地做到这一点? 我当前的解决方案(我认为这很丑陋)如下:

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:

$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();

有更好的方法吗?

谢谢!

推荐答案

让您简化代码.

$arr = \App\tableB::where("other_field", "=", $value)->lists('id')->all(); 

$res = \App\tableA::whereIn("field", $arr)->get();

与all()链接的list()将自动将您的集合转换为数组.但是,在laravel 5.0或更低版本中,您不需要all()即可将集合转换为数组.

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.

这篇关于Laravel雄辩的ORM所在位置(子查询)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆