laravel-5.1 - 分页方法不存在

标签 laravel-5.1

当我这样做时:

    $tournaments =  Tournament::paginate(Config::get('constants.PAGINATION'));

它有效,但我只需要拥有用户的锦标赛。

我也是这样的:

    $tournaments = Auth::user()->tournaments;
    $tournaments->paginate(Config::get('constants.PAGINATION'));

我在用户模型中有一个 hasMany 关系

我收到这条消息

Method paginate does not exist.

我该如何解决?看起来并不复杂,但我做不到!

编辑: @smartrahat

第二个查询的结果:Auth::user()->tournaments

Collection {#385 ▼
#items: array:1 [▼
0 => Tournament {#386 ▼
  #table: "tournament"
  +timestamps: true
  #fillable: array:17 [▶]
  #dates: array:2 [▶]
  #connection: null
  #primaryKey: "id"
  #perPage: 15
  +incrementing: true
  #attributes: array:16 [▶]
  #original: array:16 [▶]
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▶]
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}
]  
}

第一次查询的结果:

LengthAwarePaginator {#428 ▼
#total: 2
#lastPage: 1
#items: Collection {#430 ▼
#items: array:2 [▼
  0 => Tournament {#431 ▼
    #table: "tournament"
    +timestamps: true
    #fillable: array:17 [▶]
    #dates: array:2 [▶]
    #connection: null
    #primaryKey: "id"
    #perPage: 15
    +incrementing: true
    #attributes: array:16 [▶]
    #original: array:16 [▶]
    #relations: []
    #hidden: []
    #visible: []
    #appends: []
    #guarded: array:1 [▶]
    #dateFormat: null
    #casts: []
    #touches: []
    #observables: []
    #with: []
    #morphClass: null
    +exists: true
    +wasRecentlyCreated: false
  }
  1 => Tournament {#432 ▶}
]
}
#perPage: "20"
#currentPage: 1
#path: "http://laravel.dev:8000/tournaments"
#query: []
#fragment: null
#pageName: "page"
}

最佳答案

在您的问题中,您很可能在集合上调用 paginate()

在有效的答案中,您是在 Eloquent 构建器上调用 paginate()

Auth::user()->tournaments; // dynamic property for relationship, probably a collection

Auth::user()->tournaments(); // relation type object (eloquent builder)

你的答案:

$tournaments = Tournament::where('user_id',Auth::user()->id)
    ->paginate(Config::get('constants.PAGINATION'));

where 正在返回您调用 paginate 的 eloquent 构建器。

这应该会给你相同的结果:

$tournaments = Auth::user()->tournaments()->paginate(...);

关于laravel-5.1 - 分页方法不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34474975/

相关文章:

拉拉维尔 5 : How to create a router model binding on multiple parameters

php - 如何在 Laravel 5.1 中编写原始查询?

Laravel "Homestead Up"更新 VirtualBox 后无法启动虚拟机,Vagrant 表示它已经存在

css - Laravel Linkroute 不解释 HTML 而是输出为文本

javascript - 如何过滤选择选项中的数据并将其显示为报告(php : laravel framework)

mysql - 使用 Laravel Eloquent 从一个表中检索数据并按相关表列排序

php - Laravel 5.1 与 Asgard CMS,查询执行时间长

php - Laravel Ardent 多对多关系抛出错误

php - 带变量的 Laravel 模型表名

php - 将字符串转换为碳