how to create table relationship in Laravel

Published 11 months ago by Flex

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?

Dry7
Dry7
11 months ago (151,880 XP)

@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

@Dry7

)->comment = 'Project';

Isn't it

)->comment('Project');

?

Dry7
Dry7
11 months ago (151,880 XP)

@ftrillo you can use both methods

Flex

@Dry7 what is the meaning of

fk__tasks__project_id

and

'fk__tasks__task_id'
Dry7
Dry7
11 months ago (151,880 XP)

@Flex foreign key name

Please sign in or create an account to participate in this conversation.