我正在尝试显示与数据库中的各个帖子相关的评论。在我的 React 组件中显示该帖子的评论(惯性), 在 Laravel 中使用 Eloquent 关系。
这是我的 PostController:
public function show()
{
$posts = Post::all();
return Inertia::render('Posts', ['posts' => $posts]);
}
我的 Post 模型中的 Eloquent 关系:
public function comments()
{
return $this->hasMany(Comment::class);
}
这组帖子被发送到我的 react 组件,在我的 Prop (props.posts)内:
{props.posts.map((post, key) => {
console.log(post.comments);
return (
<div key={key}>
{post.title}
<ul>
// map of post.comments (with hasMany relation)
</ul>
</div>
)
})}
当登录我的帖子 map 时,我收到一个值未定义。
最佳答案
在发送给惯性之前,您需要加载评论关系
public function show()
{
$posts = Post::with('comments')->get();
return Inertia::render('Posts', ['posts' => $posts]);
}
关于reactjs - 如何在惯性 ReactJs 中应用 Laravel 模型中的 hasMany 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73775607/