【问题标题】:Laravel attribute accessor capital letter is ignoredLaravel 属性访问器大写字母被忽略
【发布时间】:2016-01-08 15:45:04
【问题描述】:

我正在使用Lumen 框架。我有一个问题,我需要为属性设置自定义访问器,但问题是数据库中的列以大写字母开头。
例如Logo。在第一个大写字母的情况下,在检索对象时不会调用访问器,我尝试了几列,名称以小写字母开头的列效果很好。

 public function getLogoAttribute($value) 

此访问器不起作用,因为列的名称是 Logo
我无法更改数据库中列的名称,但需要在我的应用程序中使用访问器。
我知道我可以更改 Eloquent 框架的来源,但也许还有其他方法可以让它工作。
谢谢。

【问题讨论】:

  • 你是如何实现访问器方法的?
  • 没关系,我使用以小写字母开头的列名以相同的方式实现它,它可以工作。
  • 保持访问器原样并尝试$model->{'Logo'},对于包含破折号的列名,我必须这样做一次。
  • 我已经试过了,它显示该字段的内容没有任何问题。

标签: php laravel eloquent accessor lumen


【解决方案1】:

我花了几个小时试图在网上找到答案,但决定自己在代码中找到这部分。
我找到了。

它位于vendor/illuminate/database/Eloquent/Model
方法public function 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);
                }

你可以在你的类中覆盖这个变量。

【讨论】:

  • 我猜你应该接受你的回答,直到我们有更好的方法来解决这个问题。此外,我认为将此问答与您的Laracasts post 交叉引用很重要,您在其中详细说明了解决方案的步骤。谢谢!
【解决方案2】:

我喜欢这个

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;
   }

【讨论】:

    猜你喜欢
    • 2021-01-29
    • 2016-06-06
    • 2022-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2021-03-20
    • 1970-01-01
    相关资源
    最近更新 更多