Issue
I send in this JSON object to the API endpoint:
[
{
"name": "John",
"city": "Berlin",
},
{
"name": "Jack",
"country": "USA",
}
]
I want to create this SQL query:
SELECT * FROM users WHERE
(`name` = "John" AND `city` = "Berlin")
OR
(`name` = "Jack" AND `country` = "USA");
I have a User
model to handle users.
What is the most simpliest way to create this SQL query with Laravel Eloquent query builder?
Solution
return User::orWhere(function (Builder $query) {
return $query->where('name', 'John')->where('city', 'Berlin');
})->orWhere(function (Builder $query) {
return $query->where('name', 'Jack')->where('country', 'USA');
})->get();
(edit) If you want to send parameter(s);
$city = 'Berlin';
$country = 'USA';
return User::orWhere(function (Builder $query) use ($city) {
return $query->where('name', 'John')->where('city', $city);
})->orWhere(function (Builder $query) use ($country) {
return $query->where('name', 'Jack')->where('country', $country);
})->get();
If you want to generate it dynamically;
public function index()
{
$parameters = [
[
'name' => 'John',
'city' => 'Berlin',
],
[
'name' => 'Jack',
'country' => 'USA',
]
];
$query = User::query();
foreach ($parameters as $item) {
$query->orWhere(function (Builder $query) use ($item) {
foreach ($item as $key => $value) {
$query->where($key, $value);
}
});
}
return $query->get();
}
Answered By - Ersoy Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.