Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

birdietorerik's avatar

How to check using IF in query

Hi!

Have this query:

 $query = DB::table('gpstrackers')
            ->select('gpstrackers.*', 'users.name')
            ->leftJoin('users', 'gpstrackers.player_id_ref', '=', 'users.id')

            ->whereIn('gpstrackers.id', function ($query) use ($from1, $to1, $golfID, $courceid) {
                $query->selectRaw('MAX(gpstrackers.id) as id')
                    ->from('gpstrackers')
                   // ->leftJoin('users', 'gpstrackers.player_id_ref', '=', 'users.id')
                   ->Join('startlists_participants', 'gpstrackers.startliste_participant_ref_id', '=', 'startlists_participants.id')
                   ->Join('startlists', 'startlists_participants.startlist_id', '=', 'startlists.id')
                   ->whereBetween('gpstrackers.regdate', [$from1, $to1])
                   ->where('gpstrackers.golfclub_id', $golfID)
                   ->where('gpstrackers.courcegolfclub_id', $courceid)
                   ->groupBy('gpstrackers.flight','gpstrackers.startliste_participant_ref_id');
            });

Value $courceid can be -99, if this is the case. NOT use ->where

How can i do this ?

0 likes
2 replies
JussiMannisto's avatar

I'm not sure I understand these sentences:

Value $courceid can be -99, if this is the case. NOT use ->where

But you can use if statements normally with query builders. You don't have to chain the function calls.

$query->selectRaw('MAX(gpstrackers.id) as id')
	->join(...)
	...
	 ->groupBy(...);

if($courceid !== -99)
	$query->where(...);

Snapey's avatar

do you mean this;

 $query = DB::table('gpstrackers')
            ->select('gpstrackers.*', 'users.name')
            ->leftJoin('users', 'gpstrackers.player_id_ref', '=', 'users.id')

            ->whereIn('gpstrackers.id', function ($query) use ($from1, $to1, $golfID, $courceid) {
                $query->selectRaw('MAX(gpstrackers.id) as id')
                    ->from('gpstrackers')
                   // ->leftJoin('users', 'gpstrackers.player_id_ref', '=', 'users.id')
                   ->Join('startlists_participants', 'gpstrackers.startliste_participant_ref_id', '=', 'startlists_participants.id')
                   ->Join('startlists', 'startlists_participants.startlist_id', '=', 'startlists.id')
                   ->whereBetween('gpstrackers.regdate', [$from1, $to1])
                   ->where('gpstrackers.golfclub_id', $golfID)

				   ->when($courceid != -99, function $q) {
					   $q->where('gpstrackers.courcegolfclub_id', $courceid)
				   }
                  
                   ->groupBy('gpstrackers.flight','gpstrackers.startliste_participant_ref_id');
            });

By the way, golf course

and for compatibility between windows and linux, its join not Join

Please or to participate in this conversation.