如何使用 Laravel 7 或 8 中的 eloquent 获取用户 table 到评论 table 外键的主键

How to get the primary key of the Users table to comments table foreign key using eloquent in Laravel 7 or 8

我想吸引或加入用户 table 进入我的 评论 table。但我不知道该怎么做 我使用 hasMany 获取所有 comments table 到 posts 。我想加入 用户 table 到

这是我的模特帖

namespace App\Models;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    class Posts extends Model
    {
        use HasFactory;
        public function comments(){
            return $this->hasMany(Comments::class,'posts_id');
        }
    }

这是我的 PostsController 我使用 hasManyposts评论 tables

namespace App\Http\Controllers;
use App\Models\Posts;
class UserController extends Controller
{
    public function index(){
        return Posts::with('comments')->get();
        return view('welcome',['authors'=>$authors]);
    }
}

我的 PostsController 使用 hasMany

的输出
   [
    {
    "id": 1,
    "post": "im in relationship now",
    "comments": [
            {
            "posts_id": 1,
            "comments_id": 1,
            "users_id": 1,
            "comments": "sweet"
            },
            {
            "posts_id": 1,
            "comments_id": 2,
            "users_id": 2,
            "comments": "grats"
            },
            {
            "posts_id": 1,
            "comments_id": 3,
            "users_id": 3,
            "comments": "wow"
            },
            {
            "posts_id": 1,
            "comments_id": 4,
            "users_id": 4,
            "comments": "grats dudes"
            }
        ]
    },
    {
    "id": 2,
    "post": "im graduate now",
    "comments": [
            {
            "posts_id": 2,
            "comments_id": 5,
            "users_id": 5,
            "comments": "stay strong"
            },
            {
            "posts_id": 2,
            "comments_id": 6,
            "users_id": 6,
            "comments": "sweets"
            },
            {
            "posts_id": 2,
            "comments_id": 7,
            "users_id": 7,
            "comments": "ayiee"
            }
        ]
    }
]

在输出上你看到评论有一个 users_id 我想加入用户 table 来获取那个 table 的信息,比如名字和用户名

在 Comment.php 模型中添加此关系

public function user() {
        return $this->belongsTo( User::class );
    }

在视图中的评论循环中

{{$comments->user->name}}

我已经解决了这个问题

return $posts = Posts::with(['user', //users who created and posted
        'comments' => function($user) {
            $user->with('users'); //users who commented 
 }])->get();