1

¿Qué diferencia hay entre estas dos consultas en cuanto a rendimiento, etc.?:

Users::query()
    ->with('roles')
    ->get();

Users::query()
    ->get()
    ->load(['roles']);
0

1 respuesta 1

2

Laravel dispone de un par métodos para, al crear una consulta, volcar los query bindings actuales y SQL. Ref Database: Query Builder # Debugging.

Con ellos notarás que no hay diferencia entre ambas consultas traducidas a mysql, y en cuanto a rendimiento prácticamente tampoco, simplemente que con la segunda puedes cargar opcionalmente la relación mas tarde:

1.

DB::connection()->enableQueryLog();
User::query()
    ->with('roles')
    ->get();
Log::debug(DB::getQueryLog());

/*
array (
    0 => 
    array (
    'query' => 'select * from `users` where `users`.`deleted_at` is null',
    'bindings' => 
    array (
    ),
    'time' => 0.59,
    ),
    1 => 
    array (
    'query' => 'select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id`, `role_user`.`created_at` as `pivot_created_at`, `role_user`.`updated_at` as `pivot_updated_at` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` in (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 13, 14, 15)',
    'bindings' => 
    array (
    ),
    'time' => 0.62,
    ),
)  
*/
DB::connection()->enableQueryLog();
User::query()
    ->get()
    ->load(['roles']);
Log::debug(DB::getQueryLog());

/*
array (
  0 => 
  array (
    'query' => 'select * from `users` where `users`.`deleted_at` is null',
    'bindings' => 
    array (
    ),
    'time' => 0.58,
  ),
  1 => 
  array (
    'query' => 'select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id`, `role_user`.`created_at` as `pivot_created_at`, `role_user`.`updated_at` as `pivot_updated_at` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` in (1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 13, 14, 15)',
    'bindings' => 
    array (
    ),
    'time' => 0.61,
  ),
)  
*/
2

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.