Search code examples
phplaravelpolymorphic-associations

How can I get the name of comments' author?


Here is my table structure:

-- users
+----+-------+
| id | name  |
+----+-------+
| 1  | John  |
| 2  | Jack  |
| 3  | Peter |
+----+-------+

-- posts
+----+---------+----------------------+-----------+
| id |  title  |         body         | author_id |
+----+---------+----------------------+-----------|
| 1  | title1  | somthing             | 2         |
| 2  | title2  | whatever             | 1         |
| 3  | title3  | anything             | 3         |
+----+---------+----------------------+-----------+

-- comments
+----+-----------------+---------+-----------+
| id |     message     | post_id | author_id |
+----+-----------------+---------+-----------+
| 1  | my message      | 3       | 2         | 
| 2  | whatever        | 1       | 3         |
+----+-----------------+---------+-----------+

Now I want to get a post with all its comments. Here is my code:

    $post= Posts::orderBy('id', 'DESC')->where('id', $request->id)->first();
    $comments = $post->comments;

Noted that I have this relation in the User model:

public function comments()
{
    return $this->hasMany('App\Comments','post_id', 'id')->orderBy('id');
}

What's my question? I also want to get the name of comments' author. I mean the name of the person who has written the comment. anyway, how can I make a relation on an existing relation?

Note: I can do that by a raw JOIN. But I want to know how can I do that by Laravel relations?


Solution

  • why you define relation with task_id?

    in user model :

    public function comments()
    {
        return $this->hasMany('App\Comments','author_id', 'id');
    }
    

    and in comment model :

    /**
     * comments belongs to a user.
     */
    public function user()
    {
        return $this->belongsTo('App\User', 'author_id', 'id');
    }
    

    now you can get a user with comments

    User::where("id",$userId)->with("comments")->orderBy('id', 'DESC')->get();
    

    if you want get post with all comments you should define relation like this for post model.

    in posts model define a relation :

    public function comments()
    {
        return $this->hasMany('App\Comments','post_id', 'id');
    }
    

    and in comments model :

    /**
     * comments belongs to a post.
     */
    public function post()
    {
        return $this->belongsTo('App\Posts', 'post_id', 'id');
    }
    

    now :

    Posts::where("id",$postId)->with("comments")->orderBy('id', 'DESC')->get();