[英]Laravel 5.4 - Skip Model Mutator
我有一個模型更改器,可在子段末尾添加隨機字符串。
public function setSlugAttribute($slug) {
$slugNumber = mt_rand(100000, 999999);
$this->attributes['slug'] = $slug."-".$slugNumber;
}
我只需要在第一次創建模型時就發生這種情況,而不必在模型更新時發生。 當模型已經存在並且彈頭已經很好時,如何跳過增幅器?
刪除您的子彈變異器,並使用creating
事件在創建之前對子彈進行變異。 例如
class MyModel extends Model
{
public function boot()
{
parent::boot();
static::creating(function ($model) {
$random = mt_rand(100000, 999999);
$model->slug = $model->slug . '-' . $random;
});
}
}
this Delete your slug mutator and use the creating
public static function boot()
{
parent::boot();
Posts::saving(function(Posts $model){
$random = mt_rand(10000, 99999);
$model->slug = str_slug($model->title). '-'. $random;
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.