Laravel使用paginate处理关系数据

时间:2018-05-20 20:30:18

标签: php laravel laravel-5.6

在我的网络应用程序中,每个内容作为帖子属于一个或多个类别,类别有很多帖子,现在当我从这段代码中获取数据时:

$categoryContents=ContentCategories::with('contents')->whereId($id)->latest()->paginate(10);

返回此输出:

    LengthAwarePaginator {#971 ▼
      #total: 1
      #lastPage: 1
      #items: Collection {#963 ▼
        #items: array:1 [▼
          0 => ContentCategories {#862 ▼
            #table: "contents_categories"
            ...
            #attributes: array:6 [▶]
            #original: array:6 [▶]
            ...
            #relations: array:1 [▼
              "contents" => Collection {#962 ▼
                #items: array:2 [▼
                  0 => Contents {#952 ▶}
                  1 => Contents {#953 ▶}
                ]
              }
            ]
            ...
          }
        ]
      }
      #perPage: 10
      #currentPage: 1
      #path: "http://127.0.0.1:8000/category/5"
      #query: []
      #fragment: null
      #pageName: "page"
    }

在这个paginator中我试图通过以下代码显示contents数组:

@foreach($categoryContents->contents_categories->contents as $content)

@endforeach

但是我收到了这个错误:

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$contents_categories

如何在paginator上显示这个结构?

我的模特:

class ContentCategories extends Model
{
    ...

    public function contents()
    {
        return $this->belongsToMany(Contents::class);
    }
}

class Contents extends Model
{
    ...

    public function categories()
    {
        return $this->belongsToMany(ContentCategories::class);
    }
}

2 个答案:

答案 0 :(得分:1)

此查询:

$categoryContents=ContentCategories::with('contents')->whereId($id)->latest()->paginate(10);

没有多大意义。您正在查询ContentCategory个ID,它将完全匹配1个结果,但您仍然使用latest(),其订单(无需在1行订购)结果和调用paginate(10),它将对结果进行分页(没有任何内容在1行上分页)。

您希望对contents进行分页,而不是父ContentCategories

// whereHas to scope it only to the category with id = `$id`
$contents = Contents::whereHas('categories', function ($subQuery) use ($id) {
        $subQuery->where('id', $id);
    })
    // Order the cotnents
    ->latest()
    // Paginate the contents
    ->paginate(10);

然后将$contents传递给您的视图并foreach传递给它:

@foreach($contents as $content)

@endforeach

答案 1 :(得分:0)

您可以按以下方式解决此问题:

  $categoryContents = ContentCategories::with('contents')->whereId($id)->latest()->paginate(10);
    $categoryContents->getCollection()->transform(function ($item) {
        return $item->contents;
    });