gpt4 book ai didi

php - 如何使用 Laravel 5.1 将空字符串更改为 null?

转载 作者:可可西里 更新时间:2023-11-01 00:05:08 27 4
gpt4 key购买 nike

在使用 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。

我在这里做错了什么?

最佳答案

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

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

return parent::setAttribute($key, $value);
}

关于空日志,除了框架的日志,你有没有检查webserver日志?

关于php - 如何使用 Laravel 5.1 将空字符串更改为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31708707/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com