Laravel 来自给定数组的查询中的多个 where 子句

Laravel multiple where clauses in query from given array

我希望标题足以描述我的问题。 我试图在 laravel 中制作一个 geosearch-function。查询本身是正确的。现在,我尝试从我的 table 中获取所有文章,这些文章与之前查询的已获取邮政编码相匹配。我使用的所有函数都可以在这里找到:Laravel 5 add results from query in a foreach to array)。但现在我想在多个或动态 where 子句(带或)中执行一个查询。 我之前查询的 print_r($zipcodes)(从邮政编码 $zipcodes = $this->getZipcodes($zipCoordinateId, $distance); 获取范围内的所有邮政编码)输出:

Array
(
[0] => stdClass Object
    (
        [zc_zip] => 13579
        [distance] => 0
    )

[1] => stdClass Object
    (
        [zc_zip] => 12345
        [distance] => 2.228867736739
    )

[2] => stdClass Object
    (
        [zc_zip] => 98765
        [distance] => 3.7191570094844
    )
)

那么当我想执行以下操作时,我在 laravel 中的查询应该如何显示?

SELECT *
FROM articles
WHERE zipcode = '13579'
OR zipcode = '98765'
OR zipcode = '12345';

提前谢谢你, 量子神论者

更新

使用 balintant 的解决方案,效果很好。这是我的代码:

// grabs all zipcodes matching the distance
$zipcodes = $this->getZipcodes($zipCoordinateId, $distance);

foreach ($zipcodes AS $key=>$val)
{
    $zipcodes[$key] = (array) $val;
}

$codes = array_column($zipcodes, 'zc_zip');

$articles = Article::whereIn('zipcode', $codes)->get();

return view('pages.intern.articles.index', compact('articles'));

您可以同时使用 whereInorWhere 范围。第一个更适合您当前的示例。此外,您可以使用 array_column 从上面的数组中获取所有真实的邮政编码。

$query->whereIn('zip', [12,34,999])->get();
// > array

更新:

当您想使用 array_column 获取数组的特定子值时(如 zc_zip),您必须首先将其子项转换为数组。 如果是模型,您必须使用 toArray() 轻松转换它。

$zip_objects = [
    (object) [ 'zc_zip' => 13579, 'distance' => 0 ],
    (object) [ 'zc_zip' => 12345, 'distance' => 2.228867736739 ],
    (object) [ 'zc_zip' => 98765, 'distance' => 3.7191570094844 ],
];

foreach ( $zip_objects AS $key=>$val )
{
    $zip_objects[$key] = (array) $val;
}

$zip_codes = array_column($zip_objects, 'zc_zip');

var_dump($zip_codes);
// > array(3) {
// >  [0]=>
// >  int(13579)
// >  [1]=>
// >  int(12345)
// >  [2]=>
// >  int(98765)
// > }