Flex's avatar
Level 4

how to create table relationship in Laravel

hello, 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');
}

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?

0 likes
5 replies
Dry7's avatar

@Flex try

Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('project_id', false, true)->index()->comment = 'Project';
            $table->integer('task_id', false, true)->nullable(); //Parent task, if exists
            $table->string('name')->nullable();

            $table->foreign('project_id', 'fk__tasks__project_id')
                ->references('id')
                ->on('projects')
                ->onDelete('cascade');
            $table->foreign('task_id', 'fk__tasks__task_id')
                ->references('id')
                ->on('tasks')
                ->onDelete('cascade');
        });

So your models will work. In order to create a subtask, simply fill in the task_id field

ftrillo's avatar

@Dry7

)->comment = 'Project';

Isn't it

)->comment('Project');

?

Flex's avatar
Level 4

@Dry7 what is the meaning of

fk__tasks__project_id

and

'fk__tasks__task_id'

Please or to participate in this conversation.