SinghWithLaravel
4 months ago
754
3
Laravel

Is it required to make relation functions in both models while we just wanna use one model.

Posted 4 months ago by SinghWithLaravel

Basically i am having two models Comments and Posts.

(1) First Part - I have to access comments of a single post. For that i can make a hasMany relation function like below.

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

While accessing, i will simply call this function with post model's instance.

(2) Second Part - Is it enough to use above relation to access comments of specific post or i need to use below relation as well. In some web pages I read that I will need to define relation function in Comments model as well.

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

I think First Part is enough to get all the comments related to a post. Second part is only needed if i need to fetch the post for a specific comment, right ?

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