【问题标题】:Laravel Sort Parent Collection by their relationship valuesLaravel 按关系值对父集合进行排序
【发布时间】:2021-03-08 19:47:09
【问题描述】:

我最近想通过使用它们的关系值对集合的父元素进行排序,所以我遇到了这样的事情并且它有效。你认为这是一个合适的方法还是我把它弄得太复杂了?

基本上,我想按日期对事件进行排序

事件与插槽是一对多的

对此的任何评论将不胜感激

干杯

 $events = Event::with(['slots' => function ($q) {
        $q->orderBy('date');
        $q->orderBy('start_time');
    }])->active()->get();
    


    $slotArray = [];
    foreach($events as $event){
        foreach ($event->slots as $slot) {
               $slotArray[$slot->id] = [ 'id' => $event->id, 'start_date' => $slot->date, 'start_time' => $slot->start_time];
        }
    }
    
    //Sort the Array of IDS
    usort($slotArray, array($this,"sortByStartDate"));

    //Find the New Set of IDS sorted by the Start Date
    $sortedEventIDs = [];
    foreach($slotArray as $value) {
        array_push($sortedEventIDs, $value['id']);
    }

    $sortedEvents = $events->sortBy(function($model) use ($sortedEventIDs){
        return array_search($model->getKey(), $sortedEventIDs);
    });

排序功能

function sortByStartDate($a, $b){
        return $a['start_date'] > $b['start_date'];
}    

【问题讨论】:

    标签: php arrays laravel sorting collections


    【解决方案1】:

    有一种 SQL 方法,看起来像这样。创建一个子选择,获取您要使用的日期并按它排序。

    Event::with(['slots' => function ($q) {
            $q->orderBy('date');
            $q->orderBy('start_time');
        }])
        ->addSelect([
            'date' => Comment::selectRaw('MAX(start_date)')
                ->whereColumn('events.id', 'comments.event_id'),
        ])->orderBy('date');
    

    只需使用 Laravel 关系并做同样的事情,虽然没有优化性能,但非常直接。

    $events = Event::with(['slots' => function ($q) {
        $q->orderBy('date');
        $q->orderBy('start_time');
    }])->active()->get();
    
    $events->sortBy(function ($event) {
        return $event->slots()->max('start_date');
    });
    

    【讨论】:

    • 谢谢@mrhn,我喜欢你的解决方案,它超级干净。
    【解决方案2】:

    你可以使用 orderBy() 函数:

    $events = Event::orderBy('start_time', 'DESC')->active()->get();
    

    对于 ID,您可以使用 sortKeys():

    $sorted = $events->sortKeys();
    
    $sorted->all();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-02
      • 2021-01-15
      • 2023-03-28
      • 2016-08-03
      • 2019-01-26
      • 2022-06-28
      • 2018-11-20
      • 2015-10-18
      相关资源
      最近更新 更多