繁体   English   中英

Laravel 8 多对多关系分页

[英]Laravel 8 pagination for many to many relation

我对类别和产品有多对多的关系。 在特定类别页面中,我想为产品添加分页。

这是我在 model 类别中的代码:

public function products() {
    return $this->belongsToMany(Product::class,
        'category_product',
        'category_id',
        'product_id'
    )
    ->where('is_published',1)
    ->orderBy('id','ASC')->paginate(5);
}

这是 CategoryController 代码:

public function show($id) {       
    $category = Category::findorfail($id);        
    return view(category.show, compact('category'); 
}

这是类别视图刀片中的分页代码:

{{ $products->links() }}

这是我得到的错误:

App\Models\Category::products must return a relationship instance.

有什么解决办法吗?

错误信息很明显,关系方法必须返回一个关系实例。 所以这两个会起作用,因为它们返回Illuminate\Database\Eloquent\Relations\BelongsToMany BelongsToMany class 类型的实例:

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');
}

您的代码将返回Illuminate\Pagination\LengthAwarePaginator的一个实例,它不会起作用:

public function products() {
    return $this->belongsToMany(Product::class,
        'category_product',
        'category_id',
        'product_id'
    )
    ->where('is_published',1)
    ->orderBy('id','ASC')->paginate(5);
}

然后在您的 controller 中,您可以执行以下操作:

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() !!}

类别 model:

public function products() {
    return $this->belongsToMany(Product::class,
        'category_product',
        'category_id',
        'product_id'
    )
    ->where('is_published',1)
    ->orderBy('id','ASC');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM