Level 8
I notice that fractal works with eager loading.
I'm using the package spatie/laravel-fractal
I don't know if this is a problem or just the way fractal works, but when i include a fractal transformer in another i get a new query for each result of the first transformer. In other words, if i list Users and include the Roles, for each user i will have a query to get the roles.
public function index(Request $request)
{
$users = User::all();
$data = Fractal::create()
->collection($users)
->transformWith(new UserTransformer())
->parseIncludes(['roles'])
->toArray();
return $this->respond([
'items' => $data
]);
}
class UserTransformer extends TransformerAbstract
{
protected $availableIncludes = [
'roles', 'notifications', 'permissions'
];
public function transform(User $user)
{
return [
'id' => (int) $user->id,
'name' => $user->name,
'email' => $user->email,
'active' => (bool) $user->is_active,
];
}
public function includeRoles(User $user)
{
return $this->collection($user->roles, new RoleTransformer());
}
}
class RoleTransformer extends TransformerAbstract
{
protected $availableIncludes = [
'permissions'
];
public function transform(Role $role)
{
return [
'id' => (int) $role->id,
'name' => $role->name,
'display_name' => $role->display_name,
];
}
}

I'm getting a query to get the role for each user i'm listing Off course i will have a pagination an will not get all users, but this is insane, is 149 queries, that can be done with only one query using join.
select * from `users`
select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` = '1'
select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` = '3'
select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` = '4'
select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` = '5'
select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` = '6'
I notice that fractal works with eager loading.
Please or to participate in this conversation.