reactjs - 如何在惯性 ReactJs 中应用 Laravel 模型中的 hasMany 关系

标签 reactjs laravel eloquent-relationship inertiajs

我正在尝试显示与数据库中的各个帖子相关的评论。在我的 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/

相关文章:

javascript - ReactJS/JS 保存/导出表单输入

php - Laravel:如何将参数传递到我的 View 并在 Form::text 和 Form::date 中显示它们?

php - 如何在 Laravel 中扩展外观?

php - Eloquent:从 'max' -> `hasMany` 关系中获取 `hasOne` 值

php - 如何将条件附加到 Eloquent 关系查询中?

javascript - React 用 React 元素替换占位符

javascript - 在 React 中使用 onchange 改变子组件的 props

php - 从一个表中获取信息并将返回的信息保存在新表中 - Laravel 5.2

php - 如何在 Laravel Eloquent 中获取不在集合中的项目?

javascript - 为什么在 DOM 渲染中将属性设置为等于自身 - React.js