【问题标题】:How can I get the name of comments' author?如何获取评论作者的姓名?
【发布时间】:2018-01-13 02:09:30
【问题描述】:

这是我的表结构:

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

现在我想获得 一个包含所有 cmets 的帖子。这是我的代码:

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

我的问题是什么?我也想知道 cmets 的作者姓名。我的意思是写评论的人的名字。无论如何,我怎样才能在现有关系上建立关系?

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

【问题讨论】:

    标签: php laravel polymorphic-associations


    【解决方案1】:

    为什么要定义与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');
    }
    

    现在您可以使用 cmets 获取用户

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

    如果您想获得所有 cmets 的帖子,您应该为帖子模型定义这样的关系。

    posts 模型中定义一个关系:

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

    在 cmets 模型中:

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

    现在:

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

    【讨论】:

    • 对不起task_id,这是一个错字,eidted。
    • 只有一个问题,除了with(),没有别的办法了吗?
    • 我已经测试了您的解决方案。但它们都不是我问题的答案。正如我在问题中提到的,我想做的就是获取 cmets 的作者姓名。
    • $selectedPost = Post::find($postId); $selectedPost->cmets()->get();
    • 这是你的答案 :) 你只需要这样做:如果你想知道评论 id 1 是给哪个用户的?评论::where("id",$commentId)->with("user")->first();
    【解决方案2】:

    你可以像这样连接两个表

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

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

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 2021-12-17
      • 2018-10-22
      • 1970-01-01
      相关资源
      最近更新 更多