我正在尝试为这样的 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 关于关系的分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!