Laravel:如何将属性传递给Eloquent模型构造函数



在数据库中保存5个属性的数据之前,我想使用strtolower((,

我在型号中使用此代码

public function setFirstNameAttribute($value)
{
$this->attributes['firstName'] = strtolower($value);
}
public function setLastNameAttribute($value)
{
$this->attributes['lastName'] = strtolower($value);
}
public function setUserNameAttribute($value)
{
$this->attributes['userName'] = strtolower($value);
}
... etc

我可以使用__construct方法代替上面的代码吗?

有两种方法,第一种是直接使用引导方法(对于模型中的小更改,如您的问题中所述(

方法1:
我们可以直接使用引导方法

<?php
namespace App;
use IlluminateDatabaseEloquentModel;

class Mymodel extends Model
{
public static function boot()
{
parent::boot();
static::saving(function ($model) {
// Remember that $model here is an instance of MyModel
$model->firstName = strtolower($model->firstName);
$model->lastName = strtolower($model->lastName);
$model->userName = strtolower($model->userName);
// ...... other attributes
});
}
}


方法2:
因此,我们可以在这里使用一个简单的trait和一个为字符串生成strtolow((的简单方法。当您在模型中执行保存、创建等操作时,必须对模型进行更大的更改时,或者即使您想在多个模型中使用相同的属性,也可以使用此选项。
创建特征MyStrtolower

<?php
namespace AppTraits;
trait MyStrtolower
{
public function mystrtolower($string)
{
return strtolower($string);
}
}

我们现在可以将这个特性附加到任何我们想要拥有mystrtolower方法的类上。

<?php
namespace App;
use IlluminateDatabaseEloquentModel;
use AppTraitsMyStrtolower;
class Mymodel extends Model
{
use MyStrtolower; // Attach the MyStrtolower trait to the model

public static function boot()
{ 
parent::boot();
static::saving(function ($model) {
// Remember that $model here is an instance of MyModel
$model->firstName = $model->mystrtolower($model->firstName);
$model->lastName = $model->mystrtolower($model->lastName);
$model->userName = $model->mystrtolower($model->userName);
// ...... other attributes
});
}
}

如果您不想为您创建的每个模型重复所有这些代码行,请使用抽象方法配置特征,以便您可以动态传递要使用小写字符串的属性名称,例如employee_nameEmployee模型,user_nameUser模型。

最新更新