dox90448 2016-06-24 03:02
浏览 322
已采纳

如何在Laravel 5中为模型中的现有字段定义访问器?

I have a model called Book for a table called books, that has a field called cover_image.

However, I want to define an accessor for the field cover_image instead of just retrieving the default value.

This is how I attempted to do this:

class Book extends Model {

    public function getCoverImageAttribute() {

         if ($this->cover_image === null) { // Not sure how to check current value?
               return "a.jpg"
         }
         return $this->cover_image; 
    } 

}

However the above of course does not work because calling $this->cover_image again would cause recursion

How can I fix this?

  • 写回答

1条回答 默认 最新

  • douyinjiao9351 2016-06-24 03:06
    关注

    You must check for the attribute instead:

    class Book extends Model {
    
        public function getCoverImageAttribute() {
             return $this->attributes['cover_image'] ?? "a.jpg"; 
        } 
    
    }
    

    This will allow you to normally use $book->cover_image as well.

    I believe the following example will also work:

    class Book extends Model {
    
        public function getCoverImageAttribute($value) {    
    
             return is_null($value) ? 'a.jpg' : $value; 
        } 
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置