【问题标题】:How to change the order of results in an Eloquent collection?如何更改 Eloquent 集合中结果的顺序?
【发布时间】:2016-07-07 21:57:37
【问题描述】:

我有一个返回类别名称的表。我获取了所有记录,但问题是它有一个我想区别对待的记录,“其他水果”。我希望它最后显示。

例如,当我从数据库中获取记录时:

Category::where('parent_category_id',  $data)->where('is_active', 1)->lists('name', 'id');

它返回的集合如下所示:

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [27] => Apple
            [346] => Other Fruits
            [350] => Papaya & Pomegranate
            [377] => Banana
            [438] => Orange & Sweet Lime
        )
)

如何将“其他水果”项移到最后?

【问题讨论】:

  • “其他商店”是否存储在数据库中?如果是,您如何识别它?
  • 对不起它的其他水果我将如何确保其他水果最后来?
  • 好的,但是“其他水果”是否存储在 DB 中?
  • @Laerte 是的,它已存储
  • 我已经改写了这个问题,以便更清楚地了解您在寻找什么 Aditya

标签: php arrays sorting laravel eloquent


【解决方案1】:

嘿嘿干脆用两条规则得到两个集合

$category = Category::where('parent_category_id',  $data)->where('is_active', 1)->lists('name', 'id');
$other = << use your rule correctly >>

然后在你的视图中使用这个集合

foreach($category as .....)
foreach($other as ....)

【讨论】:

    【解决方案2】:

    你可以试试这样的。

    $categoriesExceptOtherFruits = Category::where('parent_category_id',  $data)
            ->where('is_active', 1)
            ->where('id', '<>', $otherFruitsId);
    
    $allCategories = Category::where('parent_category_id',  $data)
            ->where('is_active', 1)
            ->where('id', $otherFruitsId)
            ->union($categoriesExceptOtherFruits)
            ->lists('name', 'id');
    

    如果您的other 类别很少,请使用like 而不是&lt;&gt;

    另一种解决方案是在您的表中创建sort 列并使用orderBy('sort', 'asc')

    当然,您可以手动重新排序集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      • 2019-09-28
      • 1970-01-01
      相关资源
      最近更新 更多