简体   繁体   中英

How to write Laravel eloquent query where (condition) and (condition2 or condition 3)

Lets say we have SQL like this

select * from cards
where (deck_id=${deck_id})
and (added_by =${user_id} or is_available = 1)

And want to write in Laravel eloquent

I tried using the following queries but the result is not same as it suppose to be.

Card::where(['deck_id'=>$deck_id,'added_by'=>$user_id])
    ->orWhere(['deck_id'=>$deck_id,'is_available'=>1])
    ->get();

Card::where(['deck_id'=>$deck_id])
        ->Where(['added_by'=>$user_id])
        ->orWhere('is_available',1)
        ->get();

Seems like you want something like this:

Card::where('deck_id', $deck_id)
   ->where(function ($query) use($user_id){
         $query->where('added_by', $user_id)
         ->orWhere('is_available', 1);
    })
   ->get();

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