Php 使用关系数据分页的Laravel
在我的web应用程序中,作为帖子的每个内容都属于一个或多个类别,类别中有许多帖子,现在当我使用以下代码从中获取数据时:Php 使用关系数据分页的Laravel,php,laravel,laravel-5.6,Php,Laravel,Laravel 5.6,在我的web应用程序中,作为帖子的每个内容都属于一个或多个类别,类别中有许多帖子,现在当我使用以下代码从中获取数据时: $categoryContents=ContentCategories::with('contents')->whereId($id)->latest()->paginate(10); @foreach($categoryContents->contents_categories->contents as $content) @endforea
$categoryContents=ContentCategories::with('contents')->whereId($id)->latest()->paginate(10);
@foreach($categoryContents->contents_categories->contents as $content)
@endforeach
即返回此输出:
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"
}
在此分页器中,我试图通过此代码在视图中显示内容数组:
$categoryContents=ContentCategories::with('contents')->whereId($id)->latest()->paginate(10);
@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);
}
}
您可以通过以下方式解决此问题:
$categoryContents = ContentCategories::with('contents')->whereId($id)->latest()->paginate(10);
$categoryContents->getCollection()->transform(function ($item) {
return $item->contents;
});
此查询:
$categoryContents=ContentCategories::with('contents')->whereId($id)->latest()->paginate(10);
没什么意义。您正在按id查询一个ContentCategory
,它将恰好匹配一个结果,但您仍在使用latest()
,它对结果进行排序(在一行上不排序),并调用paginate(10)
,它将对结果进行分页(在一行上不分页)
您希望对内容进行分页,而不是对父内容类别进行分页:
// 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
您能否帮助我修复此错误:未找到列:1054未知列“categories.id”在“where子句”
中将类别
更改为ContentCategories
表的名称,可能是content\u categories.id
如果您只是这样做会怎么样:$subQuery->where('id',$id)代码>您是否将其传递到视图?此输出是否可以帮助您:从内容分类`内部连接内容分类`内容
上的内容分类
id
=内容分类
内容分类
其中内容
id
=content\u categories\u contents
contents\u id
和categories
id
=5`