You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel循环为多用户生成通知仅插入1条数据问题求助

问题根因

你在foreach循环外部仅实例化了1次Notification模型对象。第一次循环调用save()时,框架会执行INSERT逻辑生成1条新记录,同时给当前对象绑定上刚生成的主键ID;后续循环再修改这个已有主键ID的对象属性、调用save()时,框架会判定为更新已有记录,执行UPDATE逻辑而非INSERT,所以最终只会保留1条记录,不会生成多条新通知。

修复方案

方案1:循环内实例化新模型(兼容模型事件/观察者)

每次循环时新建一个Notification模型实例,保证每次save()都触发插入逻辑:

$acc = $registrant->update([
    'approval' => 1,
    'description' => $request->description,
]);

$roleuser = User::where('is_admin', 4)->orWhere('is_admin', '3')->get();
foreach ($roleuser as $key => $value) {
    // 每次循环新建实例,避免触发更新逻辑
    $notification = new Notification();
    $notification->user_id = $value->id;
    $notification->type = 'Menunggu Pelatihan';
    $notification->title = 'Pendaftar menunggu untuk pelatihan';
    $notification->message = "halo " . $value->name . " Pendaftar dengan NIP " . $registrant->nip . " menunggu untuk pelatihan";
    $notification->save();
}

方案2:批量插入(性能更高,适合通知接收人多的场景)

先组装好所有要插入的通知数据,一次性执行批量插入,减少数据库交互次数:

$acc = $registrant->update([
    'approval' => 1,
    'description' => $request->description,
]);

$roleuser = User::where('is_admin', 4)->orWhere('is_admin', '3')->get();
$insertData = [];
$currentTime = now();
foreach ($roleuser as $value) {
    $insertData[] = [
        'user_id' => $value->id,
        'type' => 'Menunggu Pelatihan',
        'title' => 'Pendaftar menunggu untuk pelatihan',
        'message' => "halo " . $value->name . " Pendaftar dengan NIP " . $registrant->nip . " menunggu untuk pelatihan",
        'created_at' => $currentTime,
        'updated_at' => $currentTime
    ];
}
Notification::insert($insertData);

注意:批量插入不会触发模型的事件、观察者逻辑,如果你在Notification模型里写了创建时自动填充字段、发送推送之类的逻辑,请选择方案1。

内容的提问来源于stack exchange,提问作者Bayustypryg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 03:45:32