我有一些包含自定义产品的集合,我需要对这些集合产品进行分页,但是会收到错误消息。
$ collection = Collection :: where('slug',$ slug)-> where('status', 'active')-> with('products')-> first();
$ collection = Product :: with('collections')-> whereHas('collections', function($ query)use($ slug){$ query-> where('slug', $ slug)-> where('status','active')-> first(); });
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)
Product model
public function collections()
{
return $this->belongsToMany(CollectionProduct::class, 'product_id');
}
Collection model
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');
}
Controller
默认查询
public function single($slug){
$collection = Collection::where('slug', $slug)->where('status', 'active')->with('products')->first();
return view('front.collections.single', compact('collection'));
}
答案 0 :(得分:1)
耦合事物:
您正在尝试在此行中的关系查询中调用first()
方法:
$ collection =产品:: with('collections')-> whereHas('collections',function($ query)use($ slug){$ query-> where('slug',$ slug)-> where ('status','active')-> first();});
方法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
但是,如果要对产品列表进行分页,则真正需要的是paginate()
方法:
$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
此外,您的collections()
模型上的Product
方法已将product_id
列为联接表,并且正在联接到CollectionProduct
模型而不是{{1} }模型。
为您的Collection
模型尝试以下操作:
Product
答案 1 :(得分:0)
我使用以下代码并且运行良好
第一步拿到产品
$product = Product()->find($product_id);
比我得到收藏和分页
$collections = Product::find($product_id)->collections->paginate(20);
例如我在这个 site 中使用了上面的代码。