laravel 如何在视图中显示一对多数据(fetch)

laravel how to show one to many data in view (fetch ) in view

你好我正在尝试获取像 post 这样的视图中的一对多数据,而这个盛宴评论应该显示在视图中

我现在能够在数组中获取值我要在视​​图中显示什么

我的阵列控制器

public function data($id)
{
     
 $post= User::with(['Comments'=>function($query){ 
    $query->first(); 
}])->find($id);

 dd($post->toArray());

}

数组数据

array:53 [▼
  "id" => 39
  "name" => "KUMAR"
  "post" => "hello word "
  "created_at" => "2022-02-11T02:38:51.000000Z"
  "updated_at" => "2022-02-11T10:05:26.000000Z"
  "comments" => array:1 [▼
    0 => array:13 [▼
      "id" => 6
      "user_id" => "39"
      "comment" => "good post"
      "created_at" => "2022-02-11T15:13:51.000000Z"
      "updated_at" => "2022-02-11T15:13:51.000000Z"
    ]
  ]
]

我的视图控制器

public function data($id)
{
     
 $post= User::with(['Comments'=>function($query){ 
    $query->first(); 
}])->find($id);

 return view('user.post',compact('post'));

}

试试这个

public function data($id)
{
     
 $post= User::wherehas('Comments', function($query){ 
    $query->where('user_id',$id); 
})->get();

 return view('user.post',compact('post'));
}

所以你的 User 模型已经有了这个 comments 关系

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

你可以添加这个firstComment关系

    public function firstComment()
    {
        return $this->hasOne(Comment::class)->oldest(); // or ->latest()
    }

然后用这种方式获取你的User

$post = User::with(['firstComment'])->find($id);

dump($post);
dd($post->firstComment);