我对类别和产品有多对多的关系。在一个特定的类别页面中,我想为产品添加分页。
这是我在分类模型中的代码:
public function products() {
return $this->belongsToMany(Product::class,
'category_product',
'category_id',
'product_id'
)
->where('is_published',1)
->orderBy('id','ASC')->paginate(5);
}
这是类别控制器代码:
public function show($id) {
$category = Category::findorfail($id);
return view(category.show, compact('category');
}
这是类别视图刀片中的分页代码:
{{ $products->links() }}
这是我得到的一个错误:
AppModelsCategory::products must return a relationship instance.
有什么解决方案吗?
错误消息非常明显,relationship方法必须返回一个关系实例所以这两个会起作用,因为它们返回类型为IlluminateDatabaseEloquentRelationsBelongsToMany
类的实例:
public function products() {
return $this->belongsToMany(Product::class,
'category_product',
'category_id',
'product_id'
);
}
// Or
public function products() {
return $this->belongsToMany(Product::class,
'category_product',
'category_id',
'product_id'
)
// This update the internal query of the relationship instance to query the relationship later on.
->where('is_published',1)->orderBy('id','ASC');
}
您的代码将返回一个IlluminatePaginationLengthAwarePaginator
的实例,这将不起作用:
public function products() {
return $this->belongsToMany(Product::class,
'category_product',
'category_id',
'product_id'
)
->where('is_published',1)
->orderBy('id','ASC')->paginate(5);
}
然后在你的控制器中,你可以做一些类似的事情:
class CategoriesController extends Controller
{
public function show($id)
{
$category = Category::findOrFail($id);
$products = $category->products()->paginate(5);
return view('categories.show', compact('category', '$products'));
}
}
找到了一个解决方案:
类别控制器:
public function show($id) {
$category = Category::findorfail($id);
$category->setRelation('products', $category->products()->paginate(5));
return view(category.show, compact('category');
}
视图刀片:
@foreach($category->products as $product)
{{ $product->title }}
@endforeach
{!! $category->products->render() !!}
类别型号:
public function products() {
return $this->belongsToMany(Product::class,
'category_product',
'category_id',
'product_id'
)
->where('is_published',1)
->orderBy('id','ASC');
}