如何防止多次保存同一条记录

How prevent save same record many times

我有控制器从 flutter 应用程序收到 12 个请求,请求是这样的:

data.map((e) async {
      Map list = {
        'username': username,
        'club': e.club,
        'price': e.price,
        'surename': e.surname,
        'id': e.id,
        'league': e.leagueName,
      };
      try {
        var newurl = Uri.parse(url + 'create_team');
        var response =
            await http.post(newurl, body: jsonEncode(list), headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token',
        });
        var result = jsonDecode(response.body);
        print(result);
      } catch (e) {
        print('error : $e');
      }
    }).toList();

我的控制器方法:

public function create_team(Request  $request)
    {
       
        $user=User::where('username',$request->username)->first();
        
        $week = Week::where('status','active')->first();
        $week_id = $week->id;
        
        $club = Club::where('club',$request->club)->first();

        $created_team=Team::where('user_id',$user->id)->get();
        if($created_team->count()==0){
            $team = Team::create([
            'team_name'=> '',
            'season_id'=> 1,
            'week_id'=> $week_id,
            'user_id'=>$user->id,
        ]);
        $team_id = Team::where('user_id',$user->id)->where('week_id',$week_id)->first();
        $insert=UserTeam::create([
            'team_id'=> $team_id->id,
            'club_id'=> $club->id,  
        ]);
        }else{
            $team_id = Team::where('user_id',$user->id)->where('week_id',$week_id)->first();
            $insert=UserTeam::create([
                'team_id'=> $team_id->id,
                'club_id'=> $club->id,  
            ]);
        }
        return response()->json(['message' => 'Succed']);
    }

在控制器中,我检查了团队是否保存过一次,但它并不是一直有效,很多时候保存了不止一个。 现在我怎样才能停止它以节省不止一次?

您可以简单地在您的模型上使用 firstOrCreate() 方法。

Team::firstOrcreate([
    'team_name'=> '',
    'season_id'=> 1,
    'week_id'=> $week_id,
    'user_id'=>$user->id,
]);

如果已经存在,则不会创建新的团队。有关详细信息,请参阅 here