Laravel将数据库整数转换为字符串

时间:2018-08-08 07:41:07

标签: php laravel laravel-5

我正在使用Laravel 5.5,并将具有超过50列的Items表设置为Tinynt以存储值。

Item::where('id',$id)->first();

现在在我看来,我想将所有整数值替换为相应的字符串,例如

if($item->column1 == 1) { $value = 'String1'); }
if($item->column1 == 2) { $valuee = 'String2'); }

&依此类推。我知道我可以使用Laravel Mutator,但是我有50多个列和设置Mutator不能解决我的问题。我的问题与this post有关,但问题是列数。

有什么解决方法吗?

3 个答案:

答案 0 :(得分:1)

我认为50是最好的方法,但是您可以重新定义__get()魔术方法:

//your Item model class

protected $castMutators = [
   //column1 => ['1' => 'string1', 2 => 'string2'],
   //column2 => ['1' => 'string1', 2 => 'string2'],
   //...
   //column50 => ['1' => 'string1', 2 => 'string2'],
];

public function __get($name)
{
   if (in_array($name, $this->castMutators)) {
         $this->{$name} = $this->castMutators[$name][$this->name]
   }

   parent::__get($name);
}

答案 1 :(得分:1)

您可以在Eloquent模型上重写getAttributeValue()或setAttributeValue()函数,如下所示。然后,您可以将相同的访问器或更改器用于多个属性。

protected function getAttributeValue($key)
{
    $value = parent::getAttributeValue($key);

    //if the value has already been mutated, don't modify, else if
    //the key is in the array of specified attributes, mutate and return it
    if($value === $this->getAttributeFromArray($key) && in_array($key, $this->attributes_to_mutate) ) {
        $value = $this->myCustomMutator($value);
    }

    return $value;
}

setAttributeValue($ key,$ value)相同

答案 2 :(得分:1)

将数组保存到config / your_config.php

<?php

return [

    'columns' => [
        1 => 'string_1',
        2 => 'string_2',
    ],

];

用法:

config('your_config.columns')[1] // string_1
config('your_config.columns')[2] // string_2
相关问题