使用 foreach 循环时更新模型关系的数据

Update data of model relationships when using foreach loop

我是 Laravel 的新手,我正在尝试在更新函数中使用 foreach 循环和 updateOrCreate()。但是,它不起作用,并且没有错误。我有以下三个模型。

销售团队

class SalesTeam extends Model
{
    public function salesTeamLeaders()
    {
        return $this->belongsToMany(SalesTeamleader::class);
    }

    public function salesTeamMember()
    {
        return $this->belongsToMany(SalesTeamMember::class);
    }

    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

销售团队负责人

class SalesTeamLeader extends Model
{
    public function salesTeam()
    {
        return $this->hasMany(SalesTeam::class);
    }
}

销售团队成员

class SalesTeamMember extends Model
{
    public function salesTeam()
    {
        return $this->hasMany(SalesTeam::class);
    }
}

销售团队主管

class SalesTeamController extends Controller
{
    // Update
    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required',
            'description' => '',
        ]);

        $salesteam = SalesTeam::find($id);
        $salesteam->name = $request->name;
        $salesteam->description = $request->description;
        $salesteam->save();

        foreach ($request['leaders'] as $leader) {
            SalesTeamLeader::updateOrCreate([
                'salesteam_id' => $salesteam->id,
                'leader_id' => $leader
            ]);
        }


        foreach ($request['members'] as $member) {
            SalesTeamMember::updateOrCreate([
                'salesteam_id' => $salesteam->id,
                'member_id' => $member
            ]);
        }

        // Flash Message
        Session()->flash("success", "ปรับปรุงข้อมูลเรียบร้อยแล้ว!");
        
        return redirect('/admin/salesTeamDashboard');
    }
}

首先,return 简单的响应以确保您获得正确的 请求 数据和 id。您可以将 $request['leaders'] 替换为 $request->input('leaders')$request['members']$request->input('members')。您不应该将查询构建器放在 for each 循环中。而是先处理它,然后传递整个数组进行更新。由于查询需要一些时间 运行,此时您的 for 循环可能会结束并超出范围。

return response()->json([
    'request_data' => $request,
    'id' => $id,
]);

看来您只需要同步销售团队的领导和成员列表。假设 SalesTeam 模型中的关系设置正确,您可以使用 BelongsToManysync 方法来执行此操作:

$salesteam->salesTeamLeaders()->sync($request->input('leaders', []));

$salesteam->salesTeamMember()->sync($request->input('members', []));

虽然salesTeamMember应该用复数命名。