mercredi 30 septembre 2020

Laravel Eloquent query recursive relationship model with pagination

I am building a store, where I have to display to the user all products in a given category and all other products that are contained in the subsequent subcategories of the currently accessed one. The categories have the N+1 problem since there can be infinite subcategories. I want to be able to filter trough these products and also to be able to paginate them. This is my categories model:

   class CatalogCategory extends Model
   {

    public function parent()
    {
        return $this->belongsTo('App/CatalogCategory','parent_id');
    }

    public function children()
    {
        return $this->hasMany($this,'parent_id')
            ->orderBy('order_place','ASC')
            ->with('children');
    }

    /*
    *   Return products, that belong just to the parent category.
    */

    public function products()
    {
        return $this->hasMany('App\CatalogProduct','parent_id')
            ->where('is_active', 1)
            ->whereDate('active_from', '<=', Carbon::now('Europe/Sofia'))
            ->orderBy('created_at','DESC');
    }

    /*
    *   Return all products contained in the parent category and its children categories.
    */

    public function all_products()
    {
        $products = $this->products;

        foreach ($this->children as $child) {
            $products = $products->merge($child->all_products());
        }

        return $products;
    }

}

The all_products() method returns all of the products, that I want, but since it's a collection i'm unable to paginate or filter through it. My question is if there is a better way to retrieve the products and how to retrieve them so, that i can query them for filtering and paginate them?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire