从Laravel Pivot返回计算的自定义属性


Return calculated custom attribute from Laravel Pivot

我正在构建一个服务API,并希望在我的JSON响应中返回一个名为'expire_at'的计算日期,用于以下'订阅'关系。日期将基于知道'activated_at'、'interval'和'interval_type'来计算。这当然可以在前端计算,但我希望在我的API响应中方便地提供这一点。我不知道该把逻辑放在哪里。

我可以使用$ appendds属性将

放在Plan模型中,但这只在从Customer请求计划时才有效。把它放在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属性的逻辑。要做到这一点,你需要用逻辑创建pivot模型,然后告诉Laravel如何使用它。

主模型:

class Subscription extends Eloquent
{
    protected $table = 'customer_plan'; // point this to your pivot table
    protected $appends = array('expires_at');
    public function getExpiresAtAttribute()
    {
        return 'tomorrow';
    }
    public function customer()
    {
        return $this->belongsTo('Customer');
    }
    public function plan()
    {
        return $this->belongsTo('Plan');
    }
}

现在我们告诉Laravel客户和计划应该使用订阅模式。

客户模式:

class Customer extends Eloquent
{
    public function subscriptions()
    {
        return $this->hasMany('Subscription');
    }
}

计划模型:

class Plan extends Eloquent
{
    public function subscriptions()
    {
        return $this->hasMany('Subscription');
    }
}

获取数据的查询略有变化:

$customer = Customer::with('subscriptions.plan')->find($id);
return Response::json($customer);