Use two queries. An eloquent one to many is two queries.
How to receive nested db result in laravels query builder
Hi
I'm struggling with Laravels Query Builder.
My question: Is there a way to retrieve "nested" results as shown in the first case (using Eloquent) when I'm using Laravels Query Builder (second case)?
First case: If I'm using the following Eloquent query, I receive a "nested" result:
Shift::with('users')->get();
//Result:
Illuminate\Database\Eloquent\Collection {
all: [
App\Models\ShiftPlanner\Shift {
id: 1,
name: "Shift 1",
date: "2021-11-01",
begin: "09:00:00",
end: "11:00:00",
users: App\Models\UserManagement\User {
id: 8,
first_name: "Eliane",
name: "Bürgi",
...,
},
},
...
],
}
Second case: If I'm using the following Laravel Query Builder query, I receive a "flat" array:
DB::table('shifts')
->join('users' , 'shifts.user_id' , '=' , 'users.id')
->get();
//Result
Illuminate\Support\Collection {
all:
[
{
"name": "Shift 1",
"date": "2021-11-01",
"begin": "09:00:00",
"end": "11:00:00",
"first_name": "Eliane",
"name": "Bürgi",
...,
},
{
"name": "Shift 2",
"date": "2021-11-05",
"begin": "09:00:00",
"end": "11:00:00",
"first_name": "Michaela",
"name": "Kaiser",
...,
},
]
}
In the second case, I get two rows back if there are two users assigned to the layer. This is then rather tedious to output the result with the help of loops.
When you eager load relations using with() under the hood a separate query runs for each relation being loaded.
For example, if you fetch all your shifts, with users, all the shifts will be fetched with one query, and then all the users where the user id is in the list you already fetched with the first query will be loaded from the user table. The results of the two queries get shuffled together by eloquent under the hood giving you the nested structure.
You can't really do that without eloquent as it's a function OF eloquent to hydrate models, rather than just fetch raw data from the DB. If you need it in that format, use eloquent - and add on extra logic as necessary with DB::raw and whatnot
Otherwise, yea, run separate queries, and manually fiddle with the data to get what you need.
Please or to participate in this conversation.