如何使用驼峰式案例访问属性?

Laz*_*zlo 17 naming-conventions laravel eloquent

为了与我的编码风格保持一致,我想camelCase用来访问属性而不是snake_case.在没有修改核心框架的情况下,Laravel可以实现这一点吗?如果是这样,怎么样?

例:

// Database column: first_name

echo $user->first_name; // Default Laravel behavior
echo $user->firstName; // Wanted behavior
Run Code Online (Sandbox Code Playgroud)

Laz*_*zlo 23

创建自己的BaseModel类并覆盖以下方法.确保您的所有其他型号extendBaseModel.

class BaseModel extends Eloquent {

    // Allow for camelCased attribute access

    public function getAttribute($key)
    {
        return parent::getAttribute(snake_case($key));
    }

    public function setAttribute($key, $value)
    {
        return parent::setAttribute(snake_case($key), $value);
    }

}
Run Code Online (Sandbox Code Playgroud)

然后用于:

// Database column: first_name

echo $user->first_name; // Still works
echo $user->firstName; // Works too!
Run Code Online (Sandbox Code Playgroud)

这个技巧围绕着通过覆盖使用的魔法来强制关键的蛇案Model.

  • 您还必须扩展__isset()和__unset()方法.否则isset(),empty()和unset()函数将无法与驼峰大小写键一起正常工作.我花了半天时间来处理这个bug. (7认同)

Bou*_*egh 20

由于SO不允许在评论中粘贴代码片段,因此我将其作为新答案发布.

为了确保急切加载不会破坏,我不得不修改@ Lazlo的答案.当通过不同的密钥访问急切加载的关系时,它们被重新加载.

<?php

class BaseModel extends Eloquent
{

    public function getAttribute($key)
    {
        if (array_key_exists($key, $this->relations)) {
            return parent::getAttribute($key);
        } else {
            return parent::getAttribute(snake_case($key));
        }
    }

    public function setAttribute($key, $value)
    {
        return parent::setAttribute(snake_case($key), $value);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 假设你运行查询``User :: with('likesPosts')``,它将被存储为``$ user-> attributes ['likesPosts']``.但是,当你重写``getAttribute``并将所有内容更改为snake_case时,它会尝试访问``$ user-> attributes ['likes_posts']``当你写``$ user-> likesPosts``时,不存在.然后laravel将延迟加载关系,即使已经加载了关系(如likePosts).为了防止这种情况,需要使用``if``语句. (4认同)

pwy*_*wyg 6

只是想我会发布这个以防它对其他人有帮助。尽管Bouke的条目很棒,但它并没有解决使用驼峰命名法的延迟加载关系。发生这种情况时,除了其他检查之外,我们只需要检查方法名称。以下是我所做的:

class BaseModel extends Eloquent
{

    public function getAttribute($key)
    {

        if (array_key_exists($key, $this->relations)
          || method_exists($this, $key)
        )
        {
            return parent::getAttribute($key);
        }
        else
        {
            return parent::getAttribute(snake_case($key));
        }
    }

    public function setAttribute($key, $value)
    {
        return parent::setAttribute(snake_case($key), $value);
    }
}
Run Code Online (Sandbox Code Playgroud)