laravel-mongodb
laravel-mongodb copied to clipboard
hasOne relationship loading many
package ver 3.8.4
I need to eager load the last Shift for a User.
// Models\User
public function last_shift() {
return $this->hasOne('App\Models\Shift', 'employee_id')->where('start', '<=', now())->latest('start');
}
// UserRepository
$query = User::query();
$query->with(['staff_type', 'last_shift'])
->where('role_name', 'staff');
// filters...
return $query->paginate($perPage);
I would expect this to retrieve at most 1 Shift model per 1 User, however, that is not the case. It seems to eager load all of the user's shifts past now() as indicated in the Laravel Debug Bar.
This is the query that it generates:
shifts.find({
"$and": [{
"start": {
"$lte": {
"$date": {
"$numberLong": "1646417701158"
}
}
}
}, {
"employee_id": {
"$in": ["5f03114184eb3d7f857008a6", "5f16aaff18509d4349329e04", "5f3e72f89fc1cd13ef52b922", "5f55fd1d14fd4c565306a3a2", "5f55fefad2559255153cd137", "5f56002b14fd4c565306a3a5", "5f56008fd2559255153cd139", "5f80020c10edd4395334db84", "5fa2d2478230083f514a1263", "5fa8f98d52e4fd2cab052572"]
}
}, {
"deleted_at": null
}]
}, {
"sort": {
"start": -1
},
"typeMap": {
"root": "array",
"document": "array"
}
})
And for 10 users, debug bar shows 141 shift models loaded. There are no other shift queries.