Laravel, why do I have so many queries?

570 Views Asked by At

Controller

    $attendees = Attendee::with('User')->get();
    return View::make('admin.attendees.index', compact('attendees'));

Attendee model

public function user()                                                                                                                                                                                                                   |        if( !( $user->hasRole('admin') || $user->hasRole('programmer') ))
{                                                                                                                                                                                                                                        |            return Redirect::to('/');
    return $this->belongsTo('User');                                                                                                                                                                                                     |
}    

View

@foreach($attendees as $attendee)
      <td>{{link_to_route('admin.users.show', $attendee->user->username, $attendee->user->id)}}</td>
@endforeach

223 queries

select * from `users` where `users`.`id` = '4' limit 1600μs
select `roles`.*, `assigned_roles`.`user_id` as `pivot_user_id`, `assigned_roles`.`role_id` as `pivot_role_id` from `roles` inner join `assigned_roles` on `roles`.`id` = `assigned_roles`.`role_id` where `assigned_roles`.`user_id` = '4'630μs
select * from `attendees`1.24ms
select * from `users` where `users`.`id` in ('5', '1', '3', '8', '9', '10')780μs
select * from `users` where `users`.`id` = '5' limit 1680μs
select * from `users` where `users`.`id` = '5' limit 1650μs
select * from `users` where `users`.`id` = '5' limit 1680μs
select * from `users` where `users`.`id` = '5' limit 1590μs
select * from `users` where `users`.`id` = '1' limit 1
 <continues like so for each user id>

I am using phpdebugbar to show the queries.

Migration

Schema::table('attendees', function(Blueprint $table) {
         $table->foreign('user_id')->references('id')->on('users')
                                   ->onDelete('cascade')
                                   ->onUpdate('no action');

Am I doing something wrong that is causing the query to be run over and over again?

1

There are 1 best solutions below

0
On BEST ANSWER

The eager load should be the name of the relationship function, not the relationship's model, and it's apparently case sensitive:

$attendees = Attendee::with('user')->get();