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

Laravel使用Eloquent更新排除指定ID数组外所有模型数据的实现方法

实现方案

直接使用 Eloquent 提供的whereNotIn方法过滤排除指定ID数组,再调用批量更新方法即可,参考代码如下:

// 确保$ids数组不为空,避免whereNotIn传空数组抛出SQL错误
if (!empty($ids)) {
    CalendarSchedule::whereNotIn('id', $ids)
        ->update(['available' => 1]);
} else {
    // 当循环未生成任何ID时,如果需要将所有数据的available设为1,可以执行下方语句
    // CalendarSchedule::query()->update(['available' => 1]);
}

可选优化建议

如果你只需要更新当前操作关联的operator_id对应的日程数据(避免误改其他操作员的日程),可以额外增加条件过滤:

if (!empty($ids)) {
    CalendarSchedule::where('operator_id', $operator->id)
        ->whereNotIn('id', $ids)
        ->update(['available' => 1]);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:57:01