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

thatsnotwherethecartsgo's avatar

Sub Query / Union Help / Legacy

Hi Friends,

I am running in to some issue in converting a legacy query using query builder and would appreciate any advice.

public function getData($player) {

        $one = DB::table('test')
                ->selectRaw('team, count(user) as games')
                ->where('Player', $player);
        
        $stats = DB::table('test')
                ->select(DB::raw('team, count(user) as gms'))
                ->where('team', $player)
                ->groupBy('Club')
                ->orderBy('gms', 'desc')
                ->unionAll($one)
                ->toSql();

		   $stats  = DB::table($two, 'dt')
    		    ->select('*')
	        	->toSql();
                
            return $stats;

    }

Output:

select * from ((select Club, count(user) as gms from `test` where `team` = ? group by `team` order by `gms` desc) union all (select team, count(user) as games from `test` where `Player` = ?)) as `dt`

Desired:

select * from (select Club, count(user) as gms from `test` where `team` = ? group by `team` order by `gms` desc) t1 union all (select team, count(user) as games from `test` where `Player` = ?)`

What I am aiming for is to only have the query after union all in ( ) and not the first query and not alias the entire thing.

Kind Regards and Much thanks

0 likes
0 replies

Please or to participate in this conversation.