Laravel,为什么我有这么多疑问?

时间:2015-06-18 20:29:54

标签: laravel laravel-4 eloquent eager-loading

控制器

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

参加者模型

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

查看

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

223次查询

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>

我正在使用phpdebugbar来显示查询。

移植

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

我做错了导致查询一次又一次地运行吗?

1 个答案:

答案 0 :(得分:1)

渴望加载应该是关系函数的名称,而不是关系模型,并且它显然区分大小写:

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