我有以下列(is_featured、sort、created_at)。按升序排列的最大特色项目是 8 个。如果特色商品少于 8 个,则从最新的非特色商品中获取。
| id | message | is_featured | sort | created_at |
|----|---------|-------------|------|------------|
| 1 | ... | 1 | 1 | 2021-06-07 |
| 2 | ... | 1 | 2 | 2021-06-08 |
| 3 | ... | 1 | 3 | 2021-06-09 |
| 4 | ... | 1 | 4 | 2021-06-10 |
| 5 | ... | 1 | 5 | 2021-06-11 |
| 6 | ... | 0 | 0 | 2021-06-12 |
| 7 | ... | 0 | 0 | 2021-06-13 |
| 8 | ... | 0 | 0 | 2021-06-14 |
这是我目前尝试过的。
$stories = Story::where(function($query) {
$query->where('is_featured', 0)
->latest();
})->orWhere(function($query) {
$query->where('is_featured', 1)
->orderBy('sort', 'asc');
})->limit(8)
->get();
我无法理解这一点。任何帮助,将不胜感激。谢谢。
答案 0 :(得分:2)
我认为您应该将这作为两个查询并根据条件合并到结果集合中。
$featuredStories = Story::where('is_featured', 1)
->orderBy('sort', 'asc')
->limit(8)
->get();
if ($featuredStories->count < 8) {
$nonFeaturedCount = 8 - $featuredStories->count;
$nonFeaturedStories = Story::where('is_featured', 0)
->limit($nonFeaturedCount)
->get();
$stories = $featuredStories->merge($nonFeaturedStories);
} else {
$stories = $featuredStories;
}