【问题标题】:Convert fname and lname to camel case while saving from model?从模型保存时将 fname 和 lname 转换为驼峰式大小写?
【发布时间】:2018-01-19 11:34:53
【问题描述】:

我有员工表,无论用户使用模型输入如何,我都想将 fname 和 lname 列保存为驼峰式大小写。我正在使用 ardent 进行验证,还有其他方法吗?我使用了像波纹管这样的变异器,但仍然将其保存为普通外壳。我做错什么了?

protected $fillable = [
        'fname','lname'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
  protected $table     = 'employees';

  protected $guarded   = array('id', 'password');
  public static $rules = array(
    'fname' => 'required',
    'lname' => 'required'
  );

/**
     * Make sure that first name is capitalized BEFORE saving it to the database
     *
     * @param $value
     * @return string
     */
    public function setFnameAttribute($value)
    {
        $this->attributes['fname'] = ucfirst($value);
    }

    /**
     * Make sure that last name is capitalized BEFORE saving it to the database
     *
     * @param $value
     * @return string
     */
    public function setLnameAttribute($value)
    {
        $this->attributes['lname'] = ucfirst($value);
    }

【问题讨论】:

    标签: laravel mutators


    【解决方案1】:

    这些修改器是正确的,但是您需要在创建新表行时使用 Eloquent 才能使这些修改器工作:

    $employee = new Employee();
    $employee->fname = $request->fname;
    $employee->lname = $request->lname;
    $employee->save();
    

    【讨论】:

    • 没有变异器我能做到吗?有没有像 Ardent 这样的插件,我只给名字就直接保存在骆驼的情况下?
    • @Sourav 如果你想让它正确,请使用 mutators。您可以覆盖一些模型方法,但这是个坏主意。
    • 好的 .. 我如何使它成为一个全局的东西,这样我就不需要每次都在模型中编写它?
    • 但关键是你不应该让它成为一个全球性的东西。它与模型有关,这就是为什么它应该留在模型中。
    【解决方案2】:

    你确定要转换成camel_case

    public function setLnameAttribute($value)
    {
        $this->attributes['lname'] = camel_case($value);
    }
    

    【讨论】:

    • 没有变异器我能做到吗?有没有像 Ardent 这样的插件,我只给名字就直接保存在骆驼的情况下?
    • 另一种方法是覆盖模型方法,但不推荐
    猜你喜欢
    • 2011-02-27
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多