如何获得评论作者的姓名?

时间:2017-08-05 05:38:52

标签: php laravel polymorphic-associations

这是我的表结构:

-- 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         |
+----+-----------------+---------+-----------+

现在我希望发布一条包含所有评论的帖子。这是我的代码:

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

注意到我在User模型中有这种关系:

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

我的问题是什么?我还希望获得评论作者的名字。我的意思是撰写评论的人的姓名。无论如何,我怎样才能在现有关系上建立关系?

注意:我可以通过原始JOIN执行此操作。但我想知道如何通过Laravel关系来做到这一点?

2 个答案:

答案 0 :(得分:5)

为什么要定义与[snip] 2017-08-05 05:49:43.819213: I tensorflow/compiler/xla/service/cpu/compiler_functor.cc:121] NestedWhileWithScalarResult.v2: 2017-08-05 05:49:43.819244: I tensorflow/compiler/xla/service/cpu/compiler_functor.cc:121] 0x00000000 movq (%rcx), %rax 2017-08-05 05:49:43.819256: I tensorflow/compiler/xla/service/cpu/compiler_functor.cc:121] 0x00000003 movl $0, (%rax) 2017-08-05 05:49:43.819263: I tensorflow/compiler/xla/service/cpu/compiler_functor.cc:121] 0x00000009 movq 8(%rcx), %rcx 2017-08-05 05:49:43.819284: I tensorflow/compiler/xla/service/cpu/compiler_functor.cc:121] 0x0000000d nopl (%rax) 2017-08-05 05:49:43.819299: I tensorflow/compiler/xla/service/cpu/compiler_functor.cc:121] 0x00000010 movq %rcx, 16(%rcx) 2017-08-05 05:49:43.819314: I tensorflow/compiler/xla/service/cpu/compiler_functor.cc:121] 0x00000014 movq %rax, 24(%rcx) [snip] 的关系?

用户模型中的

task_id

并在评论模型中:

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

现在您可以获得有评论的用户

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

如果你想要发表所有评论,你应该为帖子模型定义这样的关系。

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

定义了一个关系:

posts

并在评论模型中:

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

现在:

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

答案 1 :(得分:2)

您可以像这样加入两个表

DB::table('comments')
    ->join('users', function ($join) {
    $join->on('comments.author_id', '=', 'users.id');
    })
    ->get();

https://laravel.com/docs/5.4/queries#joins