mercredi 3 avril 2019

Can you eager load when using a cursor on a model?

I want to iterate over a large dataset using a cursor however some information I need is in a related model.

// Iterate over all the users and execute a function for each student that they have
foreach(User::with('students')->cursor() as $user) {
    $user->students->each->executeSomething();
}

If I look at the query logs I find that a new query is being created for each user which essentially makes the eager load redundant.

  0 => array:3 [
    "query" => "select * from `users`"
    "bindings" => []
    "time" => 22.28
  ]
  1 => array:3 [
    "query" => "select `user_student`.*, `student`.`id` as `pivot_id`, `student`.`name` as `pivot_name` from `user_student` inner join `student` on `user_student`.`id` = `student`.`id` where `student`.`id` is ?"
    "bindings" => array:1 [
         0 => 1
    ]
    "time" => 0.56
  ]
  2 => array:3 [
    "query" => "select `user_student`.*, `student`.`id` as `pivot_id`, `student`.`name` as `pivot_name` from `user_student` inner join `student` on `user_student`.`id` = `student`.`id` where `student`.`id` is ?"
    "bindings" => array:1 [
         0 => 2
    ]
    "time" => 0.56
  ]


Can cursor only be used on a single query? Should I just use chunk() for this situation instead?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire