从集合中获取唯一的项目属性,而不需要foreach循环


Laravel - get the only item properties from collection without the foreach loop

我想知道是否有一种方法可以在没有foreach循环的情况下获得唯一的项目属性。由于我有一个查询,在大多数情况下,集合中只有一个项目,并且我需要仅在这种情况下更改数据透视表中的状态,我想知道是否有一些优雅的方法可以在没有foreach循环的情况下做到这一点。这就是我所说的情况:

$opponents = $quiz
            ->players()
            ->where('id', '!=', $player->id)
            ->get();
        if ($opponents->count() < 2) {
            $quiz->status = 'finished';
            $quiz->save();
            foreach ($opponents as $opponent) {
                  $quiz->players()->updateExistingPivot($opponent->id, ['status' => 'dropped']);
            }            
         }

您可以像这样使用first()函数:

 $quiz->players()->updateExistingPivot($opponents->first()->id, ['status' => 'dropped']);