Laravel Eloquent pagination on relationships(Laravel Eloquent 关于关系的分页)
问题描述
我正在尝试为这样的 Eloquent 关系分页:
I am trying to paginate a Eloquent relationship like this:
$query = Product::find(1)->options()->paginate();
但我收到以下错误:
Fatal error: Call to a member function getCurrentPage() on a non-object
我已经确认代码 $query = Product::find(1)->options() 返回一个选项集合.$query 对象似乎是 hasMany 类型.以下是我正在使用的模型类.
I have confirmed that the code $query = Product::find(1)->options() returns a collection of options. The $query object seems to be of type hasMany. Below are the model classes I am using.
class Product extends Eloquent
{
protected $table = 'products';
public function options ()
{
return $this->hasMany('ProductOption', 'product_id');
}
}
class ProductOption extends Eloquent
{
protected $table = 'product_options';
public function product()
{
return $this->belongsTo('Product', 'product_id');
}
}
eloquent 不返回关系的分页结果吗?
Does eloquent not return paginated results for relationships?
推荐答案
你不能像这样延迟加载关系分页,而是在你的产品模型中把以下函数放在你的选项下面有很多关系
You can not lazy load relational pagination like that, instead in your Product Model put the following function below your options has many relationship
public function getOptionsPaginatedAttribute()
{
return $this->options()->paginate(10);
}
这将允许您通过
$product->options_paginated
这篇关于Laravel Eloquent 关于关系的分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel Eloquent 关于关系的分页
基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何替换eregi() 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
