how to set up relationship between two models

Published 1 week 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
1 week ago (125,620 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');
    }
}
Dry7

@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
1 week ago (2,380 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.

Sign In or create a forum account to participate in this discussion.