【问题标题】:Loop through an array to query another formula which will produce a new array of results循环遍历一个数组以查询另一个公式,该公式将产生一个新的结果数组
【发布时间】:2014-11-03 09:36:30
【问题描述】:

我的第一个查询返回正确的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" }

现在,这些 ID 将超过 100 个,我现在要做的是,查看另一个表 - Locations,并匹配在其 coordinate_id 列中具有此 ID 的任何行,并返回 @987654327 @。

最初,我是这样想的:

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

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

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: php laravel foreach laravel-4


    【解决方案1】:

    而不是这个:

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

    【讨论】:

    • Jarek,一如既往的出色且详尽解释的答案。谢谢你。我确实在两个模型之间建立了关系。但是,使用最后一个公式,我在})->get(); 行上得到syntax error, unexpected '}'
    • 已修复,只是 ; 在闭包中丢失。
    • 谢谢 Jarek,一如既往,非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2018-04-09
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    相关资源
    最近更新 更多