使用构造函数时不会触发特质

问题描述 投票:0回答:1

当我使用类的构造函数时,我的特征没有被触发。我的项目使用laravel 7.0

trait LogUserDB
{
    public static function bootLogUserDB()
    {
        self::creating();

        self::updating(
            function ($model) {
                $user = Auth::user();
                if ($user !== null && $user->id >= 0 && Schema::hasColumn($model->table, 'updated_by')) {
                    $model->updated_by = $user->id;
            }
        });

        self::deleting();
    }
}

abstract class AbstractBaseModel extends Model
{
    use LogUserDB;

    public function loadInfoSchema(){}
}

这是我不能使用构造函数的类

class EmailsModel extends AbstractBaseModel
{
    protected $table = 'cad_emails';
    protected $primaryKey = "id";

    public function __construtor($request){
        /**
         * If I create the constructor my field is not updated
         */
    }

}

在我的控制器中

Class XYZController extends BaseModel 
{
    $emailModel = new EmailsModel() 
    $emailEdit  = $emailModel->find(1);
    $emailEdit->email = '[email protected]';
    $emailEdit->save() // $emailEdit->update()

    dd('end');
}

当我在没有构造函数的情况下运行此示例时,我的字段“ updated_by”将使用用户ID进行更新,而在使用构造函数时,该字段不会更新。

是什么问题?我不知道为什么会发生

php laravel traits
1个回答
0
投票

首先,您需要遵循Model.php中的构造函数签名,即:

public function __construct(array $attributes = [])
{
    // ...
}

所以,您的model应该是这样的:

public function __construtor(array $attributes = [], $request = null)
{
    parent::__construct($attributes); // This is required
}

要调用父级的构造函数,必须调用parent::__construct($attributes)方法,因为traits引导是通过constructor文件中的Model.php方法完成的。

© www.soinside.com 2019 - 2024. All rights reserved.