1

是否可以根据关联模型中关系的值对急切的集合进行排序?

火柴

$matches = Match::where('tournament_id', $tournamentId)->with([
    'playingMatch', 'playingMatch.court', 'playingMatch.playingSets', 'player', 'opponent'
])->get();

我有一个匹配列表,$matche->each用于隔离不同匹配可能处于的不同状态:

隔离匹配状态

$upcomingMatches = collect([]);
$currentMatches = collect([]);
$finishedMatches = collect([]);

// Isolate all upcoming, current, and completed matches
$matches->each(function ($match) use ($upcomingMatches, $currentMatches, $finishedMatches) {

    // Has the match been started?
    if (!is_null($match->playingMatch)) {

        // Is the match finished?
        if ($match->playingMatch->finished) {
            $finishedMatches->push($match);
        }
        else {
            $currentMatches->push($match);
        }
    }
    else {
        $upcomingMatches->push($match);
    }
});

示例 JSON

array:3 [▼
  0 => array:9 [▼
    "id" => 1
    "tournament_id" => 2
    "player_id" => 1
    "opponent_id" => 2
    "title" => "Quarter Finals"
    "scheduled_start" => "Nov 6, 2015 7:14 pm"
    "playing_match" => array:10 [▼
      "id" => 1
      "match_id" => 1
      "court_id" => 1
      "score_player" => 2
      "score_opponent" => 0
      "start_time" => "2015-11-06 11:14:36"
      "finish_time" => "2015-11-06 11:14:57" <-- sort argument
      "finished" => true
      "court" => array:5 [▶]
      "playing_sets" => array:2 [▶]
    ]
    "player" => array:5 [▶]
    "opponent" => array:5 [▶]
  ]
  1 => array:9 [▶]
  2 => array:9 [▶]
]

但是现在我已经拥有了$finishedMatches我想要的所有东西finish_time,它们位于$finishedMatches[0]->playingMatch->finish_time. 我似乎想不出一种方法可以使用 Laravel 集合来做到这一点。有任何想法吗?

4

1 回答 1

4

我相信这会成功:

$finishedMatches->sortBy(function($match){
    return $match->playingMatch->finish_time;
});

我也可能会使用过滤器而不是 each 来创建集合。

$finishedMatches = $matches->filter(function ($match) {
    return ($match->playingMatch && $match->playingMatch->finished);
});

$currentMatches = $matches->filter(function ($match) {
    return !($match->playingMatch && $match->playingMatch->finished);
});

$upcomingMatches = $matches->filter(function ($match) {
    return !($match->playingMatch);
});

我的眼睛更容易了:)

于 2015-11-06T21:05:19.333 回答