Lilan
Lilan

Reputation: 163

how to create table relationship in Laravel 5.2

I am developing project management application using laravel 5.2 and in my app user can create projects and each project have many tasks and each task have many sub tasks as well. in my table project and task table have following relationship. task model relationship with project model is

public function project()
     {
         return $this->belongsTo('App\Project');
     }

project model relationship with task table

public function tasks(){
         return $this->hasMany('App\Task');
}

I need subtasks table to store sub tasks and my now My subtask table as following

id    subtask  task_id   project_id
1       abc       2           1
2       dfg       2           1
3       frt       3           2

how can I create subtasks model in relationship with project and task table?

Updated please see my subtask migration file

 public function up()
        {
            Schema::create('subtasks', function(Blueprint $table)
            {
                $table->increments('id')->unsigned();
                $table->longText('subtask_name');
                $table->integer('task_id')->unsigned();
                $table->integer('project_id')->unsigned();
                $table->timestamps();

                $table->foreign('task_id')
                      ->references('id')->on('task')
                      ->onUpdate('cascade')
                      ->onDelete('cascade');
            });
        }

Upvotes: 0

Views: 116

Answers (1)

Channaveer Hakari
Channaveer Hakari

Reputation: 2927

User and Project table has many to many relation ship. Because each user can create many projects and a project may belong to many user.

Project and Tasks has one to many relation ship. Because each Project has many Tasks and a Task belongs to a Project

Tasks and SubTasks has one to many relation ship. Because each Task can have many Subtasks and a Subtask belongs to each user.

In User.php (Model)

public function projects(){
    return $this->belongsToMany(Project::class);
}

In Project.php (Model)

public function users(){
    return $this->belongsToMany(User::class);
}

public function tasks(){
    return $this->hasMany(Tasks::class);
}

In Task.php (Model)

public function project(){
    return $this->belongsTo(Project::class);
}

public function subtasks(){
    return $this->hasMany(SubTask::class);
}

In SubTask.php (Model)

public function task(){
    return $this->belongsTo(Task::class);
}

Usage think that you have a task and want to know all the subtasks that it has.

For Eg: Just for the sake of demonstration I am doing from command line using tinker.

php artisan tinker

$task = App\Task:whereId(1)->get(); //Get the task details with id 1

$task->subtasks; //This will fetch all the subtasks that belongs to the task

Upvotes: 0

Related Questions