[英]Laravel relationship between project and task
I have two models, Project and Tasks. 我有两个模型,项目和任务。 I have defined them as follows:
我对它们的定义如下:
class Project extends Model
{
protected $fillable = ['name'];
public function tasks() {
return $this->hasMany(Task::class);
}
}
class Task extends Model
{
protected $fillable = ['name', 'description', 'completed'];
public function project() {
return $this->belongsTo(Project::class);
}
}
I want to print list of projects (1) and for each project I want to list tasks (2) and for each task I want to show detail of that single task (3). 我要打印项目列表(1),对于每个项目,我要列出任务(2),对于每个任务,我要显示该单个任务的详细信息(3)。
To achieve (1) and (2) I have setup a projectsController (only showing relevant pieces): 为了实现(1)和(2),我设置了一个projectsController(仅显示相关部分):
class ProjectsController extends Controller
{
public function index() {
$projects = Project::all();
return view('projects.index', compact('projects'));
}
public function show(Project $project) {
return view('projects.show', compact('project'));
}
}
and routes file: 和路由文件:
Route::get('projects', array('as' => 'project-index', 'uses' => 'ProjectsController@index'));
Route::get('project/{project}', array('as' => 'project-show', 'uses' => 'ProjectsController@show'));
In the view file for (1), I'm looping through with @foreach( $projects as $project ) and for (2), I'm looping through with @foreach( $project->tasks as $task ) . 在(1)的视图文件中,我使用@foreach($ projects作为$ project)进行遍历,对于(2),我使用@foreach($ project-> tasks作为$ task)进行遍历。 All works fine.
一切正常。
For (3) however, to show a single task I clicked, I have defined a TasksController: 但是对于(3),为了显示我单击的单个任务,我定义了一个TasksController:
class TasksController extends Controller
{
public function show(Project $project, Task $task) {
return view('tasks.show', compact('task'));
}
}
and routes: 和路线:
Route::get('project/{project}/task/{task}', array('as' => 'project-tasks-show', 'uses' => 'TasksController@show'));
I have issues finding how to best accomplish (3). 我在寻找最佳完成方式方面遇到问题(3)。 In the view file, I can access the task detail as I'm passing the 'task' collection in the Taskscontroller.
在视图文件中,当我在Taskscontroller中传递“ task”集合时,可以访问任务详细信息。
I feel it is not efficient nor advisable: 我觉得这样既不高效也不建议:
Try this one, if have foreign key of project_id in task model 如果任务模型中有project_id的外键,请尝试此操作
class TasksController extends Controller
{
public function show($project, $task) {
$task = Task::where('project_id', $project)->find($task);
return view('tasks.show', compact('task'));
}
}
and routes: 和路线:
Route::get('project/{project}/task/{task}', array('as' => 'project-tasks-show', 'uses' => 'TasksController@show'));
And reply for it. 并为此答复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.