Php 使用laravel 5.6为多个字段创建一个mutator
我想创建一个mutator,它将为一个表的多个字段提供服务。我有几个字段称为:h1、h2、h3和其他字段 目前,我为每个字段(h1、h2和h3)都有一个突变子,其工作原理如下: 如果有值,则该值将插入到字段h1、h2或h3中,如果没有,则插入0Php 使用laravel 5.6为多个字段创建一个mutator,php,laravel,laravel-5.6,Php,Laravel,Laravel 5.6,我想创建一个mutator,它将为一个表的多个字段提供服务。我有几个字段称为:h1、h2、h3和其他字段 目前,我为每个字段(h1、h2和h3)都有一个突变子,其工作原理如下: 如果有值,则该值将插入到字段h1、h2或h3中,如果没有,则插入0 <?php namespace App; use Illuminate\Database\Eloquent\Model; class Custom extends Model { protected $fillable = array(
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Custom extends Model
{
protected $fillable = array(
'h1', 'h2', 'h3', 'other_field', 'other_field2'
);
public function setH1Attribute($value)
{
if(!empty($value))
$this->attributes['h1'] = $value;
else
$this->attributes['h1'] = 0;
}
public function setH2Attribute($value)
{
if(!empty($value))
$this->attributes['h2'] = $value;
else
$this->attributes['h2'] = 0;
}
public function setH3Attribute($value)
{
if(!empty($value))
$this->attributes['h3'] = $value;
else
$this->attributes['h3'] = 0;
}
}
如Alex所说,您可以使用\uu set()
,检查属性是否可填充,然后根据名称和值设置属性
public function __set($name, $value)
{
if (array_key_exists($name, $this->fillable) {
$this->attributes[$name] = !empty($value) ? $value : 0;
}
}
public function __get($name)
{
return $this->attributes[$name];
}
像这样使用它:
$custom->h1 = 'Hello';
$custom->h2 = '';
echo $custom->h1; // produces 'Hello';
echo $custom->h2; // produces 0;
请注意,您还应该处理不可填充的条件,以及获取不存在的属性。这只是一个基本的实现。@Ohgodwhy有一个很好的答案,但我会确保您是否将\u set()
覆盖为默认的Laravel功能:
public function __set($key, $value)
{
if(in_array($key, ['h1', 'h2', 'h3'])){
//do your mutation
} else {
//do what Laravel normally does
$this->setAttribute($key, $value);
}
}
模型来源:您可以使用这些方法。这是深思熟虑的。