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

binggle's avatar

how to use 'with()' in Laravel DB Query Builder ?

In this case I gave up to use ORM Eloquent .

SO I decided to use DB Query builder only.

But I want to drag 'user' model with my 'results' model .

How can I get success ?

    $bettings = DB::table('results')
            ->select('1st', '2nd', DB::raw('SUM(time_laps) as time_laps'))
            ->where('event_id', $event_id)
            ->join('type', function( $join) use( $type) {
                $join->on('results.type_id', '=', 'type.id')
                        ->where('types.key' , '=', $type) ;
            })
            ->groupBy('1st', '2nd')
            ->with('user')
            ->get();


            ->with('user')

I guess I can not use with() in Query Builder.

Actually I wish I can build ORM Eloquent query than DB Query Builder .

If it's not possible I want to drag user model with results model .

Can someone help me ?

0 likes
5 replies
tykus's avatar

I guess I can not use with() in Query Builder.

Correct.

Why was it necessary for you to drop to the Query Builder? Assuming 1st and 2nd each contains a user_id, then you would need separate relationships to the User model for each of these relations.

binggle's avatar

Because 1st and 2nd are not from users .

I really need those kind relationships model .

I wish I can find the way.

tykus's avatar

What is the user relationship then; we don't know your app... I asked Why was it necessary for you to drop to the Query Builder , which you haven't answered

Snapey's avatar
Snapey
Best Answer
Level 122

Whats wrong with;

    $bettings = Results::select('1st', '2nd', DB::raw('SUM(time_laps) as time_laps'))
            ->where('event_id', $event_id)
            ->join('type', function( $join) use( $type) {
                $join->on('results.type_id', '=', 'type.id')
                        ->where('types.key' , '=', $type) ;
            })
            ->groupBy('1st', '2nd')
            ->with('user')
            ->get();
3 likes

Please or to participate in this conversation.