Search code examples
laraveleloquent

Laravel eloquent multiple WHERE with OR AND OR and LIKE?


I have ( or am trying to make ) this query in Laravel

The problem I have is with the $orThose
I want to query LIKE.

The data in that field can be many things, but there will always be a key work like "L3" or "ICU" in the field.

Can you do a LIKE query in this case

$matchThese = ['link.hos_id' => $hos_id, 'outcome.otc_otrdischargedate' => $td];
$orThose = ['outcome.otc_outcome' => '@ICU@', 'outcome.otc_outcome' => '@I.C.U@'];

$todaysReferrals = DB::table('link')
->join('daily_link', 'link.lnk_id', '=', 'daily_link.dlk_lnkid')
->join('demographic', 'link.lnk_dmgid', '=', 'demographic.dmg_id')
->join('admission', 'link.lnk_admid', '=', 'admission.adm_id')
->join('or_call', 'admission.adm_calid', '=', 'or_call.cal_id')
->join('admission_score', 'admission.adm_scoreid', '=', 'admission_score.ascore_id')
->join('diagnosis', 'link.lnk_dgnid', '=', 'diagnosis.dgn_id')
->join('outcome', 'link.lnk_otcid', '=', 'outcome.otc_id')
->where($matchThese)
->orWhere($orThose)
->get();

Solution

  • Use like and not like with % in where() and orWhere() methods:

    ->where('column', 'like', '%pattern%')
    

    https://laravel.com/docs/5.3/queries#where-clauses

    If you need to use multiple AND do like this:

    ->where($condition)
    ->where($anotherCondition)
    

    If you want to use OR do this:

    ->where($condition)
    ->orWhere($anotherCondition)
    

    To combine multiple AND and OR do parameter grouping:

    ->where('name', '=', 'John')
    ->orWhere(function ($query) {
        $query->where('votes', '>', 100)
              ->where('title', '<>', 'Admin');
    })