Laravel在给定数组的查询中使用where子句

时间:2015-11-15 13:00:49

标签: sql laravel where-clause

我希望标题能够很好地描述我的问题。 我试图在laravel中制作一个geosearch函数。查询本身是正确的。现在我尝试从我的表中获取所有文章,这些文章与之前查询的获取的邮政编码相匹配。我在这里使用的所有功能都可以在这里找到: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';

提前谢谢你, quantatheist

更新

使用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'));

1 个答案:

答案 0 :(得分:3)

您可以同时使用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)
// > }