【问题标题】:laravel 5.5 - inject more data into paginate collectionslaravel 5.5 - 将更多数据注入分页集合
【发布时间】:2017-11-28 05:35:15
【问题描述】:

我有 2 张桌子:

profiles - 用于用户配置文件。 posts - 用于用户帖子。

posts 仅具有来自profilesuser_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() 是为了注入数据。没有?

标签: php laravel-5


【解决方案1】:

这是用户模型在用户模型内部定义一个关系方法

 class User extends Authenticatable {
   public function userPosts(){
     return $this->hasMany('App\User_post','user_id');
   }
 }

这是用户帖子模型

class User_post extends Authenticatable {
  public function users(){
    return $this->belongsTo('App\User','user_id');
 }
}

然后从您的家庭控制器中获取现有代码

 public function index() {
    $posts = Post::where('publish','=',1)->orderBy('created_at', 
     'DSC')->paginate(5);
     return view('home',['posts'=>$posts]);
}

那么在你看来

<?php  foreach ($posts->items() as $p) { 
echo $p->"column name";
echo $p->users->"column name";} ?>

【讨论】:

    【解决方案2】:

    我找到了我的解决方案here

    所以我的新代码是:

    foreach ($posts->items() as $p) {
     $profile = Profile::where('user_id','=',$p->user_id)->first();
     $p['profilename'] = $profile['name'];
     $p['profileicon'] = $profile['icon'];
     $p['profilebackground'] = $profile['background'];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      相关资源
      最近更新 更多