簡體   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