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类并覆盖以下方法.确保您的所有其他型号extend的BaseModel.
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.
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)
只是想我会发布这个以防它对其他人有帮助。尽管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)
| 归档时间: |
|
| 查看次数: |
10928 次 |
| 最近记录: |