Reputation: 199
I hope the title describes my problem good as enough.
I tried to make a geosearch-function in laravel. The queries as its own are correct. Now I try to get all articles from my table, whose match with the gotten zipcode of a former query. All functions I use you can found here: Laravel 5 add results from query in a foreach to array). But now I want to perform one query, within multiple or dynamic where clauses (with or).
The print_r($zipcodes)
of my former query (get all zipcodes in a range from a zipcode $zipcodes = $this->getZipcodes($zipCoordinateId, $distance);
) outputs:
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
)
)
So how should my query in laravel should look, when I want to perform following?
SELECT *
FROM articles
WHERE zipcode = '13579'
OR zipcode = '98765'
OR zipcode = '12345';
Thank you in advance, quantatheist
UPDATE
With the solution from balintant this is working fine. Here is my code:
// 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'));
Upvotes: 3
Views: 1565
Reputation: 2831
You can use both the whereIn
and orWhere
scopes. The first one better fits to your current example. Also, you can use array_column
to get all the real zip codes from the array above.
$query->whereIn('zip', [12,34,999])->get();
// > array
Update:
When you want to use array_column
to get the specific subvalues of the array (like zc_zip
) you must first transform it's childs to an array. If it's a model you must transform it easily with 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)
// > }
Upvotes: 3