如何使用 Eloquent 从一个模型到另一个模型通过中间 table

How To use Eloquent in From One Model to another model through intermediate table

我有三个模型

文章

id 
title 

评论

id
title
user_id
article_id

用户

id 
name

我想要实现的是 select 一篇基于其 id 的文章以及发表该评论的评论和用户信息

像这样:

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

这给了我带有相关评论的文章作为对象数组,比如评论一 - 评论二等....

我想要的而不是评论对象中的 user_id 我想让它成为用户对象

看到这张照片,这就是我到目前为止所达到的

使用 laravel 5.4

您可以使用以下内容:

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

这里'user'是你在User的评论模型中提到的关系。

如果您已经在 Schemas 中定义了外键关系,则可以为 Eloquent 关系定义函数,如以下参考文献 link 中所定义 - Laravel - Eloquent Relationships.

您可以按如下方式在模型中定义函数 -

文章-

  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');
     }
  }

评论-

  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');
     }
  }

用户-

  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);
     }
  }

现在您可以像下面这样使用 -

   $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;

等等...

最后使用 ->find() 而不是 ->get() 要好得多,因为 get() returns 一个集合。

这样您将获得您想要的单个对象而不是集合。

例如:

$commentableObj = Post::with(['comments'])
                  ->withCount(['comments'])
                  ->findOrFail($commentable->id);