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

时间:2017-09-18 16:11:43

标签: php mysql laravel eloquent relationships

我有三个型号

文章

id 
title 

注释

id
title
user_id
article_id

用户

id 
name

我想要达到的目的是根据其ID以及发表该评论的评论和用户信息选​​择一篇文章

像那样:

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

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

我想要的而不是评论对象中的user_id我希望它是一个用户对象

看到这张照片是我到目前为止所得到的

screen of what i have done

使用laravel 5.4

3 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

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

此处'用户'是您在User的评论模型中提到的关系。

答案 1 :(得分:1)

如果您在Schemas中定义了外键关系,则可以定义Eloquent Relationship的函数,如以下参考链接中所定义 - 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;

依旧......

答案 2 :(得分:0)

最好最终使用-> find()而不是-> get(),因为get()返回一个Collection。

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

例如:

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