【问题标题】:How to change empty string to a null using Laravel 5.1?如何使用 Laravel 5.1 将空字符串更改为 null?
【发布时间】:2015-07-29 18:46:18
【问题描述】:

在使用 Laravel 5.1 时,我尝试在使用 Eloquent ORM 将每个值保存到数据库之前对其进行检查。我的逻辑是,首先修剪值,如果值是空字符串"",然后将其转换为null,而不仅仅是一个空字符串。

有人建议我创建一个 Trait,它会为此覆盖 setAttribute 方法。

这就是我所做的

我在名为TrimScalarValues.php 的文件中有一个新文件夹“app\Traits”,其中包含以下代码

<?php

namespace App\Traits;

trait TrimScalarValues
{
    public function setAttribute($key, $value)
    {
        if (is_scalar($value)) {
            $value = $this->emptyStringToNull(trim($value));
        }

        return $this->setAttribute($key, $value);
    }


    /**
     * return null value if the string is empty otherwise it returns what every the value is
     *
    */
    private function emptyStringToNull($string)
    {
        //trim every value
        $string = trim($string);

        if ($string === ''){
           return null;
        }

        return $string;
    }
}

最后我有一个app\Models\Account.php 文件,其中包含以下代码

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\industry;
use App\Traits\RecordSignature;
use App\Traits\TrimScalarValues;


class Account extends Model
{
    use RecordSignature, TrimScalarValues;
    /**
     * The database table used by the model.
     *
     * @var string
    */
    protected $table = 'accounts';

    protected $primaryKey = 'account_id';

    const CREATED_AT = 'created_on';

    const UPDATED_AT = 'modified_on';

    const REMOVED_AT = 'purged_on';


    /**
     * The attributes that are mass assignable.
     *
     * @var array
    */
    protected $fillable = ['client_id','account_name', 'company_code', 'legal_name', 'created_by','modified_by','instrucations'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
    */
    //protected $hidden = ['account_id', 'remember_token'];


    protected $guarded = ['account_id'];

    /**
     * Get the industry record associated with the account.
    */
    public function industry()
    {
        return $this->hasOne(industry, industry::primaryKey);
    }

    public function pk(){

        return $this->primaryKey;
    }

}

但是每次我更新一个值时,我都会得到一个没有错误或日志的白页。

当我修改 app\Models\Account.php 并将 use RecordSignature, TrimScalarValues; 更改为 use RecordSignature; 时,我没有得到白页,但显然这些值没有被修剪并转换为 null。

我在这里做错了什么?

【问题讨论】:

    标签: php laravel traits laravel-5.1


    【解决方案1】:

    你不能在你的特质中调用$this-&gt;setAttribute()。相反,您想使用 parent:: 调用“原始”setAttribute 方法:

    public function setAttribute($key, $value)
    {
        if (is_scalar($value)) {
            $value = $this->emptyStringToNull(trim($value));
        }
    
        return parent::setAttribute($key, $value);
    }
    

    关于空日志,除了框架中的日志之外,您是否检查过网络服务器日志?

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,并通过创建一个过滤空输入字段的中间件来解决它。

      public function handle($request, Closure $next) {
          $input = $request->all();
          if ($input) {
              array_walk_recursive($input, function (&$item) {
                  $item = trim($item);
                  $item = ($item == "") ? null : $item;
              });
              $request->merge($input);
          }
          return $next($request);
      }
      

      不要忘记将自定义中间件添加到 Http/Kernel.php

      Laracasts找到这个

      【讨论】:

        【解决方案3】:

        你可能想看看这个包: https://packagist.org/packages/iatstuti/laravel-nullable-fields

        “这会创建一个特征,并允许您轻松标记在持久保存到数据库时应设置为 null 的属性。”

        我知道这篇文章很旧,当时这个包可能还不存在。

        【讨论】:

          【解决方案4】:

          您可以在模型中使用 mutator。 对于字段 account_name,mutator 应该如下所示:

          public function setAccountNameAttribute($account_name)
          {
              if(is_null($account_name))
              {
                  $this->attributes['account_name'] = null;
              }
              else
              {
                  $this->attributes['account_name'] = $account_name;
              }
          }
          

          每次你使用 Eloquent 更新或插入记录时,account_name 都会通过这个 mutator 传递。

          【讨论】:

          • 但我不想对数据库中的每个字段都这样做。如果我有很多列/表“模型”,这可能会变成。另外 is_null('') 将返回 false 这意味着我什么也没做!
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-12-09
          • 2012-08-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-28
          • 1970-01-01
          相关资源
          最近更新 更多