1.在`app\extra`下新建配置文件setting.php
~~~
<?php
return [
'img_prefix' => 'http://zyw.com/public/images'
];
~~~
2.在Image模型中
~~~
<?php
namespace app\api\model;
use think\Model;
class Image extends Model
{
protected $hidden = ['delete_time', 'id', 'from'];
public function getUrlAttr($value,$data){
$url=$value;
if($data['from']==1){
$url=config('setting.img_prefix').$value;
}
return $url;
}
}
~~~
结果
![](https://box.kancloud.cn/8853225206583c5662e8f24d11d7cfd3_1213x771.png)
优化代码
1.添加父模型BaseModel,并将其它模型继承于它
~~~
<?php
namespace app\api\model;
use think\Model;
use traits\model\SoftDelete;
class BaseModel extends Model
{
protected function prefixImgUrl($value, $data){
$finalUrl = $value;
if($data['from'] == 1){
$finalUrl = config('setting.img_prefix').$value;
}
return $finalUrl;
}
}
~~~
2.修改Image模型