【发布时间】:2017-11-28 05:35:15
【问题描述】:
我有 2 张桌子:
profiles - 用于用户配置文件。
posts - 用于用户帖子。
posts 仅具有来自profiles 的user_id,以保持表格清洁。
我的HomeController 具有获取所有已发布帖子的功能:
public function index()
{
$posts = Post::where('publish','=',1)->orderBy('created_at', 'DSC')->paginate(5);
return view('home',['posts'=>$posts]);
}
其中post 仅包含user_id 以将其链接回其所有者。如何使用$posts 中的user_id 检索用户数据(user_name、user_image)并将其附加到其特定帖子?
我试过了:
foreach ($posts->items() as $p) {
$profile = Profile::where('user_id','=',$p->user_id)->first();
$p->put('profile',$profile);
}
我得到一个错误:
调用未定义的方法 Illuminate\Database\Query\Builder::put()
我该如何解决这个问题?
【问题讨论】:
-
你为什么使用 $p->put('profile',$profile);
-
我认为
put()是为了注入数据。没有?