Laravel Map DB列名称使用适当的约定到模型中的实际DB列名称

时间:2018-03-29 02:07:36

标签: laravel laravel-5.6

我们正在构建一个门户,将第一部分现有应用程序替换为第一步,但数据库架构完全没有约定。除了缺少任何约束,索引等之外,列的名称不是描述性的,也不是蛇形的。

是否可以映射数据库表列名,以便门户网站使用正确的描述性和蛇形列名称,如first_name,但写入实际数据库列first至少使门户网站成为清理科技债务的第一步是什么?

例如,类似于如果表名不遵循惯例,可以如何设置表名(Model::table):

示例

private $columns = [
    // convention => actual
    'first_name' => 'first',
    'last_name' => 'last',
    'mobile_phone' => 'phone',
    'home_phone' => 'otherPhone', // seriously!?
];

我已经查看了ModelHasAttributes这一特性,但我仍然希望这可能存在,或者有人找到了办法将其作为临时解决方案

2 个答案:

答案 0 :(得分:1)

正确的方法是使用accessors and mutators

定义访问者

public function getFirstNameAttribute() {
    return $this->first;
}

然后,您可以按$model->first_name访问该值。

定义变异者

public function setFirstNameAttribute($value) {
    $this->attributes['first'] = $value;
}

然后,您可以改变值,例如:

$model->first_name = 'first_name';
$model->save();

答案 1 :(得分:1)

您可以为所有模型创建父类:

abstract class Model extends \Illuminate\Database\Eloquent\Model {

    protected $columns = [];

    public function attributesToArray()
    {
        $attributes = parent::attributesToArray();
        foreach ($this->columns as $convention => $actual) {
            if (array_key_exists($actual, $attributes)) {
                $attributes[$convention] = $attributes[$actual];
                unset($attributes[$actual]);
            }
        }
        return $attributes;
    }

    public function getAttribute($key)
    {
        if (array_key_exists($key, $this->columns)) {
            $key = $this->columns[$key];
        }
        return parent::getAttributeValue($key);
    }

    public function setAttribute($key, $value)
    {
        if (array_key_exists($key, $this->columns)) {
            $key = $this->columns[$key];
        }
        return parent::setAttribute($key, $value);
    }

}

然后在模型中覆盖$columns

protected $columns = [
    'first_name' => 'first',
    'last_name' => 'last',
    'mobile_phone' => 'phone',
    'home_phone' => 'otherPhone',
];
相关问题