循环遍历一个数组以查询另一个公式,该公式将生成一个新的结果数组


Loop through an array to query another formula which will produce a new array of results

我的第一个查询返回正确的ID值:

$coordinates = Coordinate::select('id')
    ->whereBetween('lat', array($minlat, $maxlat))
    ->whereBetween('lng', array($minlng, $maxlng))
    ->get();

使用DD输出结果返回(例如缩短):["original":protected]=> array(1) { ["id"]=> string(4) "1495" }

现在,将有100多个这样的ID,我现在想做的是,查看另一个表Locations,并匹配其coordinate_id列中具有此ID的任何行,然后返回all columns

最初,我的想法是:

foreach($coordinates as $coordinate)
    {
        echo(Location::where('id', '=', $coordinate));
    }

但是,这会返回一个循环!

任何帮助都将不胜感激。非常感谢。

而不是这个:

$coordinates = Coordinate::select('id')
    ->whereBetween('lat', array($minlat, $maxlat))
    ->whereBetween('lng', array($minlng, $maxlng))
    ->get();

用途:

$coordinates = Coordinate::whereBetween('lat', array($minlat, $maxlat))
    ->whereBetween('lng', array($minlng, $maxlng))
    ->lists('id'); // array of ids
// then
$locations = Location::whereIn('coordinate_id', $coordinates)->get();

它将返回您正在查找的位置模型的集合。

如果您有coordinate关系设置,也可以使用whereHas

$locations = Location::whereHas('coordinate', function ($q) use ($minlat, $maxlat, $minlng, $maxlng) {
   $q->whereBetween('lat', array($minlat, $maxlat))
     ->whereBetween('lng', array($minlng, $maxlng));
})->get();