You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中$posts += Post::where()是否可行?代码报错求助

你的写法不可行,我来帮你搞定这个问题~

首先说下为什么你的代码会报错:

  • 你没有初始化$posts变量,如果当前用户没有任何角色,循环根本不会执行,$posts就没被定义,视图自然找不到它
  • 就算用户有角色,Post::where('role_id', $role->id)返回的是查询构造器实例,不是实际的帖子集合,用+=拼接这些实例完全不符合Laravel的用法,最后传到视图的根本不是可用的帖子数据

推荐的正确写法(高效版)

直接用whereIn一次性查询,比循环多次查询数据库高效得多:

// 先获取当前用户所有角色的ID集合
$roleIds = Auth::user()->roles->pluck('id');
// 一次性查询所有匹配这些角色ID的帖子
$posts = Post::whereIn('role_id', $roleIds)->get();

return view('posts.index')->with('posts', $posts);

如果你一定要用循环(不推荐,效率低)

那得先把$posts初始化为空集合,每次查询后合并结果:

// 初始化一个空集合
$posts = collect();

foreach(Auth::user()->roles as $role){
    // 拿到当前角色对应的所有帖子集合
    $rolePosts = Post::where('role_id', $role->id)->get();
    // 合并到总集合里
    $posts = $posts->merge($rolePosts);
}

return view('posts.index')->with('posts', $posts);

这样处理后,视图就能正确拿到posts数据啦~

内容的提问来源于stack exchange,提问作者Simon Damminga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:05:55