[英]How to define an accessor in model where the field name contains a number?
[英]How to define an accessor for an existing field in a model in Laravel 5?
我有一个名为Book
的模型,该模型有一个名为books
的表,该表具有一个名为cover_image
的字段。
但是,我想为字段cover_image
定义一个访问器,而不仅仅是获取默认值。
这就是我尝试执行的操作:
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;
}
}
但是上述方法当然不起作用,因为再次调用$this->cover_image
会导致递归
我怎样才能解决这个问题?
您必须改为检查属性:
class Book extends Model {
public function getCoverImageAttribute() {
return $this->attributes['cover_image'] ?? "a.jpg";
}
}
这将使您通常也可以使用$book->cover_image
。
我相信以下示例也可以使用:
class Book extends Model {
public function getCoverImageAttribute($value) {
return is_null($value) ? 'a.jpg' : $value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.