代码之家  ›  专栏  ›  技术社区  ›  Steviewevie

将雄辩的收藏按字母顺序分块的优雅方法

  •  -2
  • Steviewevie  · 技术社区  · 6 年前

    我需要像这样从数据库中对一个集合进行排序 https://www.bodybuilding.com/store/listing.htm

    我可以写,但我可能也会失去雄辩的关系,这是不理想的。

    有什么建议吗?

    4 回复  |  直到 6 年前
        1
  •  1
  •   gbalduzzi    6 年前

    假设模型名为 Categories name 你需要按类别名称的第一个字母对它们进行分组。每个类别的第一个字母不是字母字符,将在“#”符号下分组:

    $collection = Categories::get();
    $grouped = $collection->groupBy(function ($item, $key) {
        $letter = $item->name[0];
        if (ctype_alpha($letter)) {
            return $letter;
        }
        return '#';
    });
    
        2
  •  0
  •   Steviewevie    6 年前

    mapToGroups 是我要找的。这是我的解决办法。

    public function chunkByAlpha(Collection $collection)
    {
        return $collection->mapToGroups(function($item, $key) {
    
            return ($this->isAlpha($item->name[0]) ? [strtoupper($item->name[0]) => $item] : ['#' => $item]);
        });
    }
    
    public function isAlpha($toCheck)
    {
        return preg_match("/^[a-zA-Z]+$/", $toCheck);
    }
    
        3
  •  0
  •   Jane    6 年前

    看起来很普通 foreach() 就够了

    $ordered = [];
    foreach ($items as $item) {
        $key = ctype_alpha($item->attribute[0]) ? $item->attribute[0] : 'other';
        $ordered[$item->attribute[0]][] = $item;
    }
    

    上面生成一个以字母为键的assoc数组,并将所有none alpha项放入其他

        4
  •  -1
  •   Jimmy Martinez    6 年前

    https://laravel.com/docs/5.7/eloquent#retrieving-models

    $listing = App\Store::where('first_letter', 'a')
                   ->orderBy('name', 'desc')
                   ->take(10)
                   ->get();
    

    如果你需要更具体的东西,你可以创建 Scopes https://laravel.com/docs/5.7/eloquent#query-scopes