简体   繁体   中英

Laravel eloquent orm query using orwhere clause

Hi I have been using this query to retrieve data based on orWhere clause

$q->where('created', $date);
$q->where(function ($query) {
  $query->where('gender', 'Male')
        ->where('age', '>=', 18);
})->orWhere(function($query) {
  $query->where('gender', 'Female')
        ->where('age', '>=', 30);   
})->orWhere(function($query) {
  $query->where('gender', 'Orthodox')
        ->where('age', '>=', 35);

first orWhere clause is working perfectly, however 2nd isnt. It seems to be a scope issue, ie something with ()

Group your conditions properly and it should be fine.

$q->where('created', $date);
$q->where(function ($query) {
    $query->where(function ($query) {
        $query->where('gender', 'Male')
            ->where('age', '>=', 18);
    })->orWhere(function ($query) {
        $query->where('gender', 'Female')
            ->where('age', '>=', 30);
    })->orWhere(function ($query) {
        $query->where('gender', 'Orthodox')
            ->where('age', '>=', 35);
    });
});

Use an additional where() closure:

$q->where('created', $date);
$q->where(function ($q) {
     $q->orWhere(function($query) {
        $query->where('gender', 'Male')
            ->where('age', '>=', 18);
     })->orWhere(function($query) {
        $query->where('gender', 'Female')
            ->where('age', '>=', 30);   
     })->orWhere(function($query) {
        $query->where('gender', 'Orthodox')
            ->where('age', '>=', 35);
     });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM