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

laracoft's avatar

MySQL query with belongsTo

  1. I call DB::statement() to run a complex query involving aggregate functions, variables and subqueries in order to generate a report, basically, I don't think it can be reproduced in a readable manner with eloquent.
  2. However, on each row, there are also fields like user_id, project_id etc
  3. My question is, is there an easy way to write $record->user->name without having to write additional queries?
0 likes
3 replies
tykus's avatar

You can make Model instances by mapping over the array/Collection of query results.

// Your existing query
$results = DB::select(/* your complex query */); // returns an array

// Map over the Collection and `make` Model instances (replace Model with your class)
$models = new Illuminate\Database\Eloquent\Collection($results)
    ->map(fn($object) => Model::make((array) $object));

// Optionally load the relations on the Eloquent Collection
$models->loadMissing(['project', 'user']);
1 like
laracoft's avatar

@Tray2

thanks, you reminded me that i had implemented such a pattern before

1 like

Please or to participate in this conversation.