Created
March 26, 2021 08:39
-
-
Save yavgel85/6929370b563ba28b7e3b400b26f22dbb to your computer and use it in GitHub Desktop.
Transform brackets into an Eloquent query #laravel #db
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// What if you have and-or mix in your SQL query, like this: | |
// ... WHERE (gender = 'Male' and age >= 18) or (gender = 'Female' and age >= 65) How to translate it into Eloquent? | |
// This is the wrong way: | |
$q->where('gender', 'Male'); | |
$q->orWhere('age', '>=', 18); | |
$q->where('gender', 'Female'); | |
$q->orWhere('age', '>=', 65); | |
// The order will be incorrect. The right way is a little more complicated, using closure functions as sub-queries: | |
$q->where(function ($query) { | |
$query->where('gender', 'Male') | |
->where('age', '>=', 18); | |
})->orWhere(function($query) { | |
$query->where('gender', 'Female') | |
->where('age', '>=', 65); | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment