应用程序的管理员有权列出用户的每个项目。现在写,我能够列出项目,但是无论URL的唯一ID,它们都一起列出。
// Admin form case controller
public function adminforms (Project $project){
$users = User::get();
return view('smiledesign.adminforms', compact('users', 'project'));
}
///Records controller
public function records(user $users, project $project){
$project = project::get();
$users = user::get();
return view ('/smiledesign/records' , compact( 'users','project'));
}
<table class="table">
<thead>
<tr>
<th>Dr Name</th>
<th>User Id</th>
<th>Email</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td> <a href="/smiledesign/{{$user->id}}/records">{{$user->name}}</a></td>
<td> <a href="/smiledesign/{{$user->id}}/records">{{$user->id}}</a></td>
<td> <a href="/smiledesign/{{$user->id}}/records">{{$user->email}}</a></td>
</tr>
</tbody>
@endforeach
</table>
// Records view
<table class="table table-striped table-bordered" id="table_id">
<thead>
<tr>
<th>Case Number</th>
<th>Case Form</th>
<th>Patient Name</th>
<th>Date Created</th>
<th>Status</th>
</tr>
</thead>
@foreach ($project as $project)
<tbody>
<tr>
<td> <a href="/smiledesign/{{$project->id}}/show">{{$project->case_number}}</a></td>
@if ($project->services0)
<td> <a href="/smiledesign/{{$project->id}}/show">{{$project->services0}}</a></td>
@elseif ($project->services1)
<td> <a href="/smiledesign/{{$project->id}}/show">{{$project->services1}}</a></td>
@elseif ($project->services2)
{{-- <td> <a href="/smiledesign/{{$project->id}}/show">{{$project->services2 . ' ' . $project->mockup0}}</a></td> --}}
<td> <a href="/smiledesign/{{$project->id}}/show">{{$project->services2 . ' ' . $project->mockup0 . ' ' . $project->mockup1}}</a></td>
@endif
<td> <a href="/smiledesign/{{$project->id}}/show">{{$project->first_name . ' ' . $project->last_name}}</a></td>
<td> <a href="/smiledesign/{{$project->id}}/show">{{$project->created_at}}</a></td>
<td> <a href="/smiledesign/{{$project->id}}/show">{{$project->concerns}}</a></td>
</tr>
</tbody>
@endforeach
</table>
当我单击adminforms用户的链接时,我想看到的是特定用户的每个项目。相反,我访问的每个链接都可以看到所有用户的所有项目
答案 0 :(得分:1)
应该在数据库中以及模型本身中定义项目与用户之间的关系。
按照我的解释,一个用户可以处理多个项目,而一个项目可以有多个用户,这将是多对多关系。有了这个结论,我将选择一个抽象的表设置,如下所示:
function users()
{
$this->belongsToMany(User::class, 'project_users', 'project_id', 'user_id');
}
function projects()
{
$this->belongsToMany(Project::class, 'project_users', 'user_id', 'project_id');
}
如果您读过this piece of documentation,那么一切都说得通。
$users = User::with('projects')->get();
或
$projects = Project:with('users')->get();
现在,每个用户实例都有一个项目集合。如果没有,那么您需要在数据库中添加一条记录,以将项目与该用户耦合起来。
foreach($users as $user)
{
foreach($user->projects as $project)
{
echo "$user->name works on project $project->name" . PHP_EOL;
}
}
或
foreach($projects as $project)
{
foreach($project->users as $user)
{
echo "$user->name works on project $project->name" . PHP_EOL;
}
}
我的说明针对性能进行了优化。您也可以只在->projects
上调用$user
,而无需在查询中使用with('projects')
,但这意味着您将立即触发查询。由于这类代码易于在foreach
语句中使用,因此您可能在foreach
语句中进行查询,该语句被称为N+1 query problem。