【问题标题】:Laravel - get the only item properties from collection without the foreach loopLaravel - 从没有 foreach 循环的集合中获取唯一的项目属性
【发布时间】:2017-01-24 08:21:40
【问题描述】:

我想知道有没有办法在没有 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']);
            }            
         }

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-27
      • 2021-05-04
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      相关资源
      最近更新 更多