我有包含自定义产品的集合,我需要对这些集合产品进行分页,但收到错误消息。
################################################################################################
$collection=Product::with('collections')-
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'shopping.product_id' doesn't exist (SQL: select * from `collection_products` inner join `product_id` on `collection_products`.`id` = `product_id`.`collection_product_id` where `products`.`id` = `product_id`.`product_id` and `slug` = test and `status` = active limit 1)
产品型号
public function collections()
{
return $this->belongsToMany(CollectionProduct::class, 'product_id');
}
集合模型
public function collection(){
return $this->belongsToMany(CollectionProduct::class);
}
public function products(){
return $this->belongsToMany(Product::class, 'collection_products', 'collection_id', 'product_id');
}
CollectionProduct model
public function collection()
{
return $this->belongsTo(Collection::class, 'collection_id','id');
}
控制器
默认查询
public function single($slug){
$collection = Collection::where('slug', $slug)->where('status', 'active')->with('products')->first();
return view('front.collections.single', compact('collection'));
}
两件事:
您正试图在以下行中调用关系查询内部的first()
方法:
$collection=Product::with('collections')-
方法first()
和get()
用于执行查询,因此您应该将它们放在雄辩方法链的末尾:
$collection = Product::with('collections')
->whereHas('collections', function($query) use($slug) {
$query->where('slug', $slug)->where('status', 'active');
})
->get();
https://laravel.com/docs/5.7/eloquent#retrieving-models
但是,如果您想对产品列表进行分页,那么您真正需要的是page ate()
方法:
$collection = Product::with('collections')
->whereHas('collections', function($query) use($slug) {
$query->where('slug', $slug)->where('status', 'active');
})
->paginate(20); // will return 20 products per page
https://laravel.com/docs/5.7/pagination
此外,您的Products
模型上的集合()
方法将product_id
列为连接表,并且正在连接到集合产品
模型而不是集合
模型。
为您的Products
模型尝试以下方法:
public function collections()
{
return $this->belongsToMany(Collection::class, 'collection_products', 'product_id', 'collection_id');
}
我使用下面的代码,工作得很好
获得产品的第一步
$product = Product()->find($product_id);
然后我会收集和分页
$collections = Product::find($product_id)->collections->paginate(20);
例如,我在这个网站上使用了上面的代码。