Laravel雄辩的分页关系 [英] Laravel Eloquent pagination on relationships
问题描述
$ query = Product :: find(1) - > ;选项() - >分页();
但是我收到以下错误:
致命错误:调用非对象的成员函数getCurrentPage()
我已经确认代码 $ query = Product :: find(1) - > options()
返回一组选项。 $ query
对象似乎是类型 hasMany
。以下是我正在使用的示范类。
class产品扩展Eloquent
{
保护$ 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');
}
}
雄辩没有为关系返回分页结果? p>
你不能懒惰地加载关系分页,而是在你的产品模型中放下下面的功能你的选项有很多关系
public function getOptionsPaginatedAttribute()
{
return $ this-> options() - > paginate 10);
}
这将允许您调用您的关系数据的分页
$ product-> options_paginated
I am trying to paginate a Eloquent relationship like this:
$query = Product::find(1)->options()->paginate();
But I get the following error:
Fatal error: Call to a member function getCurrentPage() on a non-object
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');
}
}
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);
}
This will allow you to call the pagination on your relational data by
$product->options_paginated
这篇关于Laravel雄辩的分页关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!