how to set up relationship between two models

Published 2 months ago by Flex

hi, I have two models in My Laravel app as Task and Comment. Task model

<?php

namespace App;

use App\User;
use App\Auth;
use App\Project;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
     protected $fillable = ['task_name', 'body', 'assign','priority','duedate','project_id'];
}

Comment

<?php

namespace App;

use App\User;
use Auth;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['comments', 'project_id', 'user_id'];

}

in My app one task has many comments and one comment contain relate with one task. so now I need established relationship between these two models. how can do this?

martinbean
Dry7
Dry7
2 months ago (134,770 XP)

@Flex

class Task extends Model
{
     protected $fillable = ['task_name', 'body', 'assign','priority','duedate','project_id'];
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

class Comment extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['comments', 'project_id', 'user_id'];

    public function task()
    {
        return $this->belongsTo('App\Task');
    }
}
kifabzar

thanks for answer.. :)

kifabzar

Flex
Flex
2 months ago (3,770 XP)

@Dry7 I have some problem here with your answer that means in Task model you have used comments with "s" to end

public function comments()
    

but in Comment model you have used task with out "s" to end

public function task()

what is this different.

martinbean

@flex A task has many comments; a comment belongs to only a single task.

Please read the Laravel documentation on one-to-many relationships, as it’s all explained in there.

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