Php 使用Laravel Eloquent自动设置属性
我有一些属性,在使用Php 使用Laravel Eloquent自动设置属性,php,laravel,eloquent,model,Php,Laravel,Eloquent,Model,我有一些属性,在使用create()或save()方法时需要自动设置 型号: 控制器 我需要保存random\u列值,如您所见,该值在模型本身中定义,而无需从控制器传递它 请注意,如果我使用: SampleModel::create([ 'name' => 'Jeff', 'random_column' => true // or anything other than string ]); 它可以工作并设置值,但是
create()
或save()
方法时需要自动设置
型号:
控制器
我需要保存random\u列
值,如您所见,该值在模型本身中定义,而无需从控制器传递它
请注意,如果我使用:
SampleModel::create([
'name' => 'Jeff',
'random_column' => true // or anything other than string
]);
它可以工作并设置值,但是有没有办法避免每次都传递该值,而只是在模型中自动设置它?您尝试过吗?将
boot()
方法添加到您的SampleModel
:
protected static function boot()
{
parent::boot();
static::creating(function (SampleModel $model) {
$model->random_column = 'Random column';
});
}
每次对
SampleModel
调用->create()
时,Creating都将触发该操作。您是否尝试过?将boot()
方法添加到您的SampleModel
:
protected static function boot()
{
parent::boot();
static::creating(function (SampleModel $model) {
$model->random_column = 'Random column';
});
}
每次对
SampleModel
调用->create()
时,Creating都会触发。谢谢,使用$model->save()
时,我遇到了以下错误:函数嵌套级别达到最大值“256”,正在中止代码>但是现在您删除了它,它工作得非常好!谢谢,使用$model->save()
时,我遇到了以下错误:函数嵌套的最大级别达到了“256”,正在中止代码>但是现在您删除了它,它工作得非常好!
protected static function boot()
{
parent::boot();
static::creating(function (SampleModel $model) {
$model->random_column = 'Random column';
});
}