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

Orgil's avatar
Level 2

Query builder access relationship's method

Can Query Builder access relationship's methods like Eloquent ?

// Eloquent
$comments = User::find(1)->comments

// Query builder
$comments = DB::table('table')->join('table')->where('condition')->paginate(n)
$comments->user->name
0 likes
5 replies
jekinney's avatar

Query Builder != Eloquent.

Eloquent doesn't use joins, but active record way of getting related tables (simple queries versus one larger query).

SO no.

Snapey's avatar

if you use a join then all the fields are in the same 'row' of the response whereas eloquent provides nested objects

but I think you can use with() in a query

1 like
fitdut's avatar

Not really but laravel has many functions that can probably help with what you're trying to do.

First off you can only call a relationship function on a model and a DB query returns a collection of stdClass objects. You can however, convert these to models using the hydrate function:

$comments = DB::table('table')->join('table')->where('condition')->get();
$comments = Comment::hydrate($comments->toArray());

In your example you are using the paginator so you would need to hydrate each page of comments:

$comments = DB::table('table')->join('table')->where('condition')->paginate();
$comments = Comment::hydrate($comments->items());

This then gives you a collection of Comment models and you can call the user relationship on each of them. You can't call the relationship on all at once like in your example. If you know all the comments have the same user you can just call the relationship on the first comment:

$comments->first()->user->name;

Alternatively you could load all the users into the collection at which point you can access each comments' user using only one query:

$comments->load('user');
foreach ($comments as $comment) {
    $comment->user->name;
}

A word of caution though: Any columns that have the same name in your tables (e.g. the id column) will be merged and have the value of the final table in the join queries. The following query will provide comments with the correct ids in the id column:

$comments = DB::table('users')->join('comments', 'comments.user_id', '=', 'users.id')->where('condition')->get();

This query will not:

$comments = DB::table('comments')->join('users', 'comments.user_id', '=', 'users.id')->where('condition')->get();

This isn't a problem if you are just calling the relationship on the model as that only uses the user_id column. As long as that is unique among the tables involved you will be fine. If you try to save the models to the database though you will start running into trouble.

3 likes
Snapey's avatar

so why not just use eloquent if you want the relations to be objects?

Please or to participate in this conversation.