我有一个任务管理器,可以为每个用户分配任务。我有这4个数据库(我只显示了讨论所需的列)
用户:
--------------------------
| id | username |
---------------------------
| 1 | peterg |
----------------------------
| 2 | louisg |
----------------------------
任务:
-----------------------------------------------------
| id | title | project_id |
------------------------------------------------------
| 1 | Finsih hw | 1 |
---------------------------------------------------
| 2 | cut grass | 4 |
----------------------------------------------------
用户和任务的数据透视表user_task:
----------------------------------------------
| id | task_id | user_id |
---------------------------------------------
| 1 | 1 | 1 |
--------------------------------------------
| 2 | 1 | 2 |
---------------------------------------------
| 1 | 2 | 2 |
--------------------------------------------
| 1 | 2 | 4 |
--------------------------------------------
最后是我的项目表:
---------------------------
| id | title |
-----------------------------
| 1 | first_title |
---------------------------
| 2 | second_title |
------------------------------
这是与任务的用户关系
public function assignedTasks()
{
return $this->belongsToMany('RL\Tasks\Task', 'user_task')
->orderBy('priority', 'ASC')
->orderBY('created_at', 'DESC')
->where('stage', '=', 1);
}
我的Laravel显示此页面的路线是/{username}/assigned-task
所以当这条路线被点击时,有一个服务类可以获取该用户的所有任务
public function assignedTasks($username)
{
$user = $this->member->getUserIdByUsername($username);
if(!$user) throw new UsernameNotFoundException;
$tasks = $user->assignedTasks;
return $tasks;
}
我的html用于显示已分配的任务:
<div id="assignments">
@foreach(array_chunk($tasks->all(), 3) as $row)
<div class="row">
<?php $task_id = [];?>
@foreach($row as $task)
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{{$task->title}}.</h3>
</div>
<div class="panel-body">
<p>{{$task->description}}</p>
<p><strong>Project: </strong>{{$task->project->title}}</p>
<p class=""><strong>Priority: </strong>{{$task->priority}}</p>
<p class="right"><strong>Stage: </strong>{{$task->stage}}</p>
<a href="">Details</a>
</div>
</div>
</div>
@endforeach
</div>
@endforeach
</div>
这很好但是当我检查SQL时我注意到每次我尝试{{$task->project->title}}
运行select * from项目,所以如果我有50个分配的任务,那是sql运行的50倍。我怎样才能在多对多关系中加载项目?
答案 0 :(得分:0)
您必须在getUserIdByUsername($username);
方法中使用预先加载。
例如,它看起来像
User::with('tasks')->where('username',$username)->get();
现在,当你打电话给$tasks = $user->assignedTasks;
时,它只会获取一次数据。
阅读热切的文档Loading