访问器: 当我们想去获取当前模型不存在的字段的时候就会自动调用访问器函数(大驼峰)
class SmallVideo extends Model
{
protected $table = 'small_video';
protected $guarded = ['id'];
public $timestamps = false;
protected $appends = ['cover', 'frame']; // ①: 添加参数到 JSON 中
public function getCoverAttribute() // ②: 构建访问器
{
$v = $this;
$av = SmallVideoImage::where('id',$v->image_id)->first();
if(!$av) return SmallVideoImage::find(1);
return $av;
}
public function getFrameAttribute()
{
$v = $this;
$av = SmallVideoImage::where('id',$v->frame_id)->first();
if(!$av) return SmallVideoImage::find(1);
return $av;
}
}
查到的数据结构:
{
"id": 72,
"posterId": 80,
"nickname": "小红",
"cover": { // 这个字段就是通过访问器添加进来的
"id": 40,
"width": 1080,
"height": 1920,
"url": "http://tanker.com/photo.jpg"
},
"frame": { // 这个属性也是通过访问器添加进来的
"id": 1,
"width": 368,
"height": 640,
"url": "http://tanker.com/photo.jpg"
},
}
修改器: 当我们想去修改一个不存在该模型中的字段的时候就会自动调用修改器函数(大驼峰)
和上面一样