Php 忽略Laravel属性访问器大写字母
我正在使用Php 忽略Laravel属性访问器大写字母,php,laravel,eloquent,accessor,lumen,Php,Laravel,Eloquent,Accessor,Lumen,我正在使用Lumen框架。我有一个问题,我需要为属性设置自定义访问器,但问题是数据库中的列以大写字母开头。 例如Logo。如果是第一个大写字母,则在检索对象时不调用访问器,我尝试了几列,名称从小写字母开始的列非常有效 public function getLogoAttribute($value) 此访问器不起作用,因为列的名称是Logo 我无法更改数据库中列的名称,但需要在应用程序中使用访问器。 我知道我可以更改雄辩的框架的来源,但可能还有其他方法可以让它工作。 谢谢 我花了几个小时试图
Lumen
框架。我有一个问题,我需要为属性设置自定义访问器,但问题是数据库中的列以大写字母开头。例如
Logo
。如果是第一个大写字母,则在检索对象时不调用访问器,我尝试了几列,名称从小写字母开始的列非常有效
public function getLogoAttribute($value)
此访问器不起作用,因为列的名称是Logo
我无法更改数据库中列的名称,但需要在应用程序中使用访问器。
我知道我可以更改雄辩的框架的来源,但可能还有其他方法可以让它工作。
谢谢 我花了几个小时试图在网上找到答案,但后来决定自己在代码中找到这一部分。
我找到了 它位于供应商/照明/数据库/雄辩/模型中 方法
公共函数attributesToArray()
修改此方法的以下部分
$mutatedAttributes = $this->getMutatedAttributes();
// We want to spin through all the mutated attributes for this model and call
// the mutator for the attribute. We cache off every mutated attributes so
// we don't have to constantly check on attributes that actually change.
foreach ($mutatedAttributes as $key) {
if (! array_key_exists($key, $attributes) ) {
if(array_key_exists(ucfirst($key), $attributes)) {
$key = ucfirst($key);
}
else {
continue;
}
}
/**
* Indicates if the model mutated attributes can have different case from ex. User_comments instead of user_comments.
*
* @var bool
*/
public $upperCaseMutatedAttributes = false;
if($this->upperCaseMutatedAttributes && array_key_exists(ucfirst($key), $attributes)) {
$key = ucfirst($key);
}
如果列名称中有多个大写字母,则此操作将不起作用
对于这个问题,这是一个糟糕的解决方案,只需按照约定为您命名数据库列,您就不会有任何问题(在我的情况下,我可以更改列名)
更新
您也可以这样修改类
$mutatedAttributes = $this->getMutatedAttributes();
// We want to spin through all the mutated attributes for this model and call
// the mutator for the attribute. We cache off every mutated attributes so
// we don't have to constantly check on attributes that actually change.
foreach ($mutatedAttributes as $key) {
if (! array_key_exists($key, $attributes) ) {
if(array_key_exists(ucfirst($key), $attributes)) {
$key = ucfirst($key);
}
else {
continue;
}
}
/**
* Indicates if the model mutated attributes can have different case from ex. User_comments instead of user_comments.
*
* @var bool
*/
public $upperCaseMutatedAttributes = false;
if($this->upperCaseMutatedAttributes && array_key_exists(ucfirst($key), $attributes)) {
$key = ucfirst($key);
}
您可以在类中重写此变量。我喜欢这样做
protected $appends = ['image'];
public function getImageAttribute(){
$img = null;
$value = $this->attributes['Image'];
if ($value) {
if (strpos($value, 'baseurl') !== false) {
$img = $value;
} else {
$img = 'prefixurl' . $value;
}
}
return $img;
}
你是如何实现访问器方法的?没关系,我是用以小写字母开头的列名来实现它的。保持访问器不变,然后尝试
$model->{'Logo'}
,对于包含破折号的列名,我必须这样做一次。我已经尝试过了,它显示了这个领域的内容,没有任何问题。我想你应该接受你的答案,直到我们有更好的方法来解决这个问题。此外,我认为重要的是交叉参考本Q&A和您的计划,其中详细说明了解决方案的步骤。谢谢你!