[英]laravel 5.5 - inject more data into paginate collections
I have 2 tables: 我有2张桌子:
profiles
- for user profiles. profiles
-用于用户配置文件。 posts
- for user posts. posts
用于用户帖子。
posts
only has a user_id
from profiles
, to keep the table clean. posts
仅具有profiles
的user_id
,以保持表整洁。
my HomeController
have a function that get all published posts: 我的
HomeController
有一个获取所有已发布帖子的函数:
public function index()
{
$posts = Post::where('publish','=',1)->orderBy('created_at', 'DSC')->paginate(5);
return view('home',['posts'=>$posts]);
}
which post
only contains user_id
to link it back to its owner. 该
post
仅包含user_id
即可将其链接回其所有者。 How can I use the user_id
from $posts
to retrieve user data (user_name, user_image) and append it to its specific post? 如何使用
$posts
的user_id
检索用户数据(user_name,user_image)并将其附加到其特定的帖子中?
I tried: 我试过了:
foreach ($posts->items() as $p) {
$profile = Profile::where('user_id','=',$p->user_id)->first();
$p->put('profile',$profile);
}
and I get an error: 我得到一个错误:
Call to undefined method Illuminate\\Database\\Query\\Builder::put()
调用未定义的方法Illuminate \\ Database \\ Query \\ Builder :: put()
How can I resolve this? 我该如何解决?
this is user model define a relationship method inside the user model 这是用户模型,在用户模型内定义一种关系方法
class User extends Authenticatable {
public function userPosts(){
return $this->hasMany('App\User_post','user_id');
}
}
this is user post model 这是用户帖子模型
class User_post extends Authenticatable {
public function users(){
return $this->belongsTo('App\User','user_id');
}
}
then from your homecontroller the existing code 然后从您的家庭控制器中获取现有代码
public function index() {
$posts = Post::where('publish','=',1)->orderBy('created_at',
'DSC')->paginate(5);
return view('home',['posts'=>$posts]);
}
then in your view 然后在您看来
<?php foreach ($posts->items() as $p) {
echo $p->"column name";
echo $p->users->"column name";} ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.