Laravel使用正确的约定将数据库列名称映射到模型中的实际数据库列名称 [英] Laravel Map DB Column Names Using Proper Convention to Actual DB Column Names in Model

查看:110
本文介绍了Laravel使用正确的约定将数据库列名称映射到模型中的实际数据库列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为第一步,我们正在构建一个门户来替换现有应用程序的一部分,但是数据库模式绝对没有任何约定.除了没有任何约束,索引等之外,列的名称不是描述性的,也不是蛇形的.

We're building a portal to replace part of an existing application as step one, but the DB schema holds to absolutely no conventions. Aside from the lack of any constraints, indexes, etc the names of columns are not descriptive and not snake-cased.

是否可以映射数据库表的列名,以便门户网站使用诸如first_name之类的适当的描述性和用蛇括起来的列名称,但要写入实际的数据库列first,至少使门户网站成为迈向第一步清理技术债务?

Is it possible to map DB table column names so that the portal uses proper descriptive and snake-cased column names like first_name but writes to the actual database column first to at least have the portal be a first step towards cleaning up the tech debt?

例如,类似于如果表名不遵循约定可以设置表名(Model::table)的方式:

For example, similar to how the table name (Model::table) can be set if the table name doesn't follow convention:

示例

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

我已经仔细研究了ModelHasAttributes的特征,但我仍然希望这种情况可能存在,或者有人找到了一种解决方法,作为一种临时解决方案.

I've looked through Model and the HasAttributes trait, but I'm still hoping that this might exist, or someone has found a way to do this as a temporary solution.

推荐答案

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

You can create a parent class for all your models:

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',
];

这篇关于Laravel使用正确的约定将数据库列名称映射到模型中的实际数据库列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆