【发布时间】:2014-07-28 18:51:35
【问题描述】:
我正在构建一个服务 API,并希望在我的 JSON 响应中为下面的“订阅”关系返回一个名为“expire_at”的计算日期。日期将根据已知的 'activated_at'、'interval' 和 'interval_type' 计算。这当然可以在前端计算,但我想在我的 API 响应中方便地提供这个。我不知道该把逻辑放在哪里。
我可以使用 $appends 属性将其放入计划模型中,但这仅在向客户请求计划时才有效。将其放入 CustomerController 将需要遍历每个客户的每个订阅。
我应该将计算每个订阅的此日期的逻辑放在客户结果中的哪个位置?以上地方是我仅有的两个选择吗?
客户 JSON 结果:(添加了“expire_at”)
{
id: 4327,
name: "Test Company",
created_at: "2014-05-29 21:12:37",
updated_at: "2014-05-29 21:12:37",
subscriptions: [
{
id: 93754,
name: "Test standard plan",
description: "An example subscription plan",
...
created_at: "2014-05-29 21:12:37",
updated_at: "2014-05-29 21:12:37",
activated_at: "2014-05-29 00:00:00",
active: true,
renewal_active: false,
// expire_at: "2014-06-28 00:00:00",
interval: 1,
interval_type_name: "Monthly"
}
]
}
计划模型:
class Plan extends Eloquent {
protected $guarded = array('id');
protected $hidden = array('pivot');
public function customers()
{
return $this->belongsToMany('Customer');
}
}
客户模型:
class Customer extends Eloquent {
protected $guarded = array('id');
public function users()
{
return $this->hasMany('User');
}
public function subscriptions()
{
return $this->belongsToMany('Plan')->withPivot('activated_at as activated_at', 'active as active', 'renewal_active as renewal_active');
}
}
客户控制器
public function show($id)
{
$customer = Customer::with('subscriptions')->find($id);
return Response::json($customer);
}
【问题讨论】:
-
考虑到这一点,我认为最好在我的订阅控制器中定期计算“expire_at”日期(即关于付款等事件) (上面未显示)并实际存储/更新数据库中的日期。这将减少每次获取客户和/或订阅时完成的计算量。
标签: php json laravel-4 eloquent