该API使用Laravel 资源集合功能为客户端提供JSON响应。存在复杂的应用程序逻辑时如何处理应用程序编码结构。
这是Model类。 BookTransaction
模型具有type
标志,以区分记录是借用(b)还是返回(r)。
class Member extends Model
{
protected $table = 'lms_members';
protected $primaryKey = 'member_id';
protected $guarded = ['member_id'];
public function user()
{
return $this->belongsTo('User');
}
public function transactions()
{
return $this->hasMany(BookTransaction::class, 'member_id', 'member_id');
}
}
资源和资源集合:
class Member extends JsonResource
{
public function toArray($request)
{
return [
'member_id' => $this->member_id,
'user_id' => $this->user_id,
'name' => $this->name,
'joined_date' => $this->joined_date,
'barcode' => $this->barcode,
'rfid' => $this->rfid,
'image' => $this->image,
'remark' => $this->remark,
'user' => $this->whenLoaded('user'),
];
}
}
class MemberCollection extends ResourceCollection
{
public function toArray($request)
{
return [
'data' => $this->collection,
'meta' => [
'result_count' => $this->collection->count(),
]
];
}
}
目标是利用Resource类为数据创建响应,该响应将包含比所描述的更多的属性。
例如,如果要创建具有总借阅数,总回报数和两者之间的区别,如何干燥呢?