从hasMany关系和paginate获取所有对象

时间:2015-09-10 04:06:12

标签: php pagination laravel-5 relationship

在我的Laravel应用程序中,我有一个类别列表页面。当用户点击某个子类别时,我想列出所有产品并对该结果使用分页。我已经在子类别ID的帮助下列出了与该子类别相关的所有产品:

public function subcategoryListing($slug){
    $products = Subcategory::find($idofSubcat)->products;
    return view('pages.subcategorylisting')
        ->with(array(
            'products' => $products,
        ));
}

此结构涉及三个类:类别子类别产品。他们被宣布如下:

分类

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use App\Subcategory;

class Category extends Model
{
    protected $table = 'category';

    public $timestamps = false;

    public function subCategory(){
        return $this->hasMany('App\Subcategory', 'category_id');
    }
}

子类别

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subcategory extends Model
{
    protected $table = 'subcategory';

    public $timestamps = false;

    public function products(){
        return $this->hasMany('App\Products');
    }
}

产品

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Products extends Model
{
    protected $table = 'products';
}

对于每个模型类,我有一个表,具有以下结构:

Category
- id
- category_name

SubCategory
- id
- category_id
- subcategory_name

Products
- id
- subcategory_id
- product_title
- description
- price

我想要的是在页面中对从查询中检索到的结果进行分页。有没有更好的方法来获取与products关联的subcategory并对其进行分页?

2 个答案:

答案 0 :(得分:6)

在Eloquent(Laravel的ORM)中,当您将关系称为属性($subCategory->products)时,它会根据关系类型返回相关对象或对象集合(属于,有很多,... )。相反,如果您将其称为函数($subCategory->products()),则会获得QueryBuilder个实例。

请参阅{{3>},关系方法与<动态属性以获取更多详细信息。

无论如何,使用关系方法,您可以为您的收藏调用paginate()。然后,考虑到这一点,您可以稍微更改代码以获得您想要的内容:

public function subcategoryListing($slug) {

    // I'm supposing here that in somewhere before 
    // run the query, you set the value to $idofSubcat 
    // variable

    $products = Subcategory::find($idofSubcat)->products()->paginate();
    return view('pages.subcategorylisting')
        ->with(array(
            'products' => $products,
        ));
}

答案 1 :(得分:2)

我无法理解你的一些初始功能:

// $slug is not being used anywhere within the function
public function subcategoryListing($slug){

    // $idOfSubcat isn't passed to this function so will throw an error
    $products = Subcategory::find($idofSubcat)->products;

    return view('pages.subcategorylisting')
        ->with(array(
            'products' => $products,
        ));
}

如果您要做的就是对属于特定Products的{​​{1}}进行分页,假设您拥有subcategory_id,则以下代码将起作用:

subcategory_id

然后,您可以将此分页集合返回到您正在执行的视图中:

$products = Product::where('subcategory_id', $idofSubcat)->paginate();