引入模型观察者后,设置在提交所有事务后处理事件后报错

mQuery

问题描述

引入模型观察者后,模型观察者中设置

public bool $afterCommit = true;

在提交所有事务后处理事件后报错,改为false即无错误。

laravel文档地址:

https://learnku.com/docs/laravel/10.x/eloquent/14888#3bfe46

程序代码

<?php

namespace app\observer;

use app\model\User;
use isszz\hashids\facade\Hashids;

class UserObserver
{
     /**
     * 在提交所有事务后处理事件
     *
     * @var bool
     */
    public bool $afterCommit = true; //注:设置true后报错

    public function creating(User $user): void
    {
        $user->nickname = substr_replace($user->mobile, '****', 3, 4);
        $avatars = config('avatar');
        $user->avatar = $avatars[array_rand($avatars)];
    }

    /**
     *  处理用户「创建」事件。
     */
    public function created(User $user): void
    {
        $user->hash_code = Hashids::mode('other')->encode($user->id);
        $user->save();
        $user->detail()->firstOrCreate();
    }
}

截图报错信息里报错文件相关代码

controller代码:
截图
model代码:
截图
报错信息:
截图

操作系统及workerman/webman等框架组件具体版本

版本:php 8.1
系统:macOS 14.2.1 与 debian_11_9_x64
引入composer包如下图:
截图

363 1 0
1个回答

10bang
之前illuminate/database和illuminate/events为8.0版本不会报错
 public bool $afterCommit = true;设置属性后无效果
 现在illuminate/database和illuminate/events升级到最新版$afterCommit = true后确实会报错了
  • tanhongbin 2024-07-04

    我现在 illuminate/database illuminate/events 10.47 根本就不触发 模型事件 protected static function booted(): void
    {
    //创建模型之前执行
    static::creating(function ($model) {
    queueSend('ceshi',['a' => 'creating']);
    echo 'creating';
    //dump($model);
    });
    //创建模型之后执行
    static::created(function ($model) {
    echo 'created';
    //dump($model);
    });
    //修改之前
    static::updating(function (User $model) {
    queueSend('ceshi',['a' => 'updating']);
    echo 'updating';
    //dump($model);
    });
    //修改之后
    static::updated(function ($model) {
    queueSend('ceshi',['a' => 'updated']);
    echo 'updated';
    //dump($model);
    });
    static::saving(function ($model) {
    echo 'saving';
    queueSend('ceshi',['a' => 'updated']);
    //dump($model);
    });
    static::saved(function ($model) {
    echo 'saved';
    queueSend('ceshi',['a' => 'updated']);
    //dump($model);
    });
    static::deleting(function ($model) {
    echo 'deleting';
    //dump($model);
    });
    static::deleted(function ($model) {
    echo 'deleted';
    //dump($model);
    });

    }完全不触发
×
🔝