根据排序Id对产品排序



我有一个基于sortId返回产品的表单,我将它插入到postman中,一切都工作,但orderderby并不适用于所有产品。

$products = Product::with('raffles')
->whereHas('categories',function($q2) use ($categoryId) {
$q2->where('category_id', $categoryId);
})
->where(function ($query) use ($sortId) {
//Default order
if ($sortId == 1) {
$query->orderBy('id');
} 
//Has raffle
if ($sortId == 2) {
$query->whereHas('raffles',function($q2) {
$q2->where('active', 1);
})->orderBy('created_at', 'desc');
} 
//More sold tickets
if ($sortId == 3) {
$query->whereHas('raffles',function($q2) {
$q2->where('active', 1)
->orderBy('sold_ticket', 'asc');
});
} 
})
->paginate(10);

在你的代码中

$query->whereHas('raffles',function($q2) {
$q2->where('active', 1)
->orderBy('sold_ticket', 'asc');
});

应该

$query->whereHas('raffles',function($q2) {
$q2->where('active', 1);
})
->orderBy('sold_ticket', 'asc');

也许如果你使用when()方法重写查询?

$products = Product::with('raffles')
->whereHas('categories',function ($q2) use ($categoryId) {
$q2->where('category_id', $categoryId);
})
->when($sortId == 1, function ($query) {
$query->orderBy('id');
})
->when($sortId == 2, function ($query) {
$query->whereHas('raffles', function ($q2) {
$q2->where('active', 1);
})
->orderBy('created_at', 'desc');
})
->when($sortId == 3, function ($query) {
$query->whereHas('raffles', function ($q2) {
$q2->where('active', 1);
})
// sort the relationship column
->with([
'raffles' => function ($q2) {
$q2->orderBy('sold_ticket', 'asc');
}
]);
})
->paginate(10);

这应该工作,如果$sortId'1','2''3'。如果$sortId为对于像'1,2,3'这样的字符串或数组,您需要做一些不同的事情。

$sortId = explode(',' $sortId); // ['1', '2', '3']

,在条件下,不执行$sortId == 1,执行in_array('1', $sortId)

最新更新