如何通过中间表在一个模型中使用Eloquent到另一个模型

i have three models

Article

id 
title 

Comment

id
title
user_id
article_id

User

id 
name

what i wanna achieve is to select one article based on its id with comments and user info that made that comment

like that :

$article = Article::find($id -- say 1)->with('comments' -- this is a relation in Article Model)->get(); 

this gives me article with related comments as an array of objects say comment one - comment two etc ....

what i want instead of user_id in comment object i wanna it to be a user object

see this pic thats what i reached so far

screen of what i have done

using laravel 5.4

You can use following:

$articles = Article::find($id)->with('comments', 'comments.user')->get();

Here 'user' is the relationship you mentioned in the comments model for User.

If you have defined the foreign key relationship in Schemas, you can define functions for Eloquent Relationship as defined in following reference link - Laravel - Eloquent Relationships.

You can define functions in models as follows -

Article -

  class Article extends Model
  {
     ...

     public function comments(){

         // Accessing comments posted to that article.

         return $this->hasMany(\App\Comment::class);
     }

     // Create a foreign key to refer the user who created the article. I've referred it here as 'created_by'. That would keep relationship circle complete. You may ignore it if you want.

     public define user(){

         // Accessing user who posted the article

         return $this->hasOne(\App\User::class, 'id', 'created_by');
     }
  }

Comment -

  class Comment extends Model
  {
     ...

     public function article(){

         // Accessing article to which the particular comment was posted

         return $this->hasOne(\App\Article::class, 'id', 'article_id');
     }

     public function user(){

         // Accessing user who posted the comment

         return $this->hasOne(\App\User::class, 'id', 'user_id');
     }
  }

User -

  class User extends Models
  {
     ...

     public function articles(){

         // Accessing articles posted by a user

         return $this->hasMany(\App\Article::class);
     }

     public function comments(){

         // Accessing comments posted by a user

         return $this->hasMany(\App\Comment::class);
     }
  }

Now you can use like following -

   $article = Article::findOrFail($id);
   $comments = $article->comments;
   $article_user = $article->user;
   $comment_user = Comment::findOrFail($commnet_id)->user;
   $users_comments = User::findOrFail($user_id)->comments;
   $users_articles = User::findOrFail($user_id)->articles;

and so on...