通过数据透视表的created_at字段排序的多对多关系

时间:2014-09-26 10:14:24

标签: many-to-many eloquent

我建立了一个不错的CRM系统,我将联系人与组织链接

在我的联系模式中,我有:

public function organizations()
{
    return $this->belongsToMany('Organization')
      ->withPivot('ContractStatus')
      ->withTimestamps()
      ->orderBy('created_at', 'desc');
}

问题是它现在正在对组织表的创建日期进行排序。 但是为了回显每个联系人的作业历史列表,我想在数据透视表的created_at字段上订购,因为那是Contact en Organization之间的合同的日期。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

问题是,关系上的数据透视表字段使用前缀pivot_别名,因此它们不会与相关的表字段冲突。

话虽如此,你需要这个:

public function organizations()
{
    return $this->belongsToMany('Organization')
      ->withPivot('ContractStatus')
      ->withTimestamps()
      ->orderBy('pivot_created_at', 'desc');
}

请注意,只有在使用withTimestamps()时才会有效,否则会出现unknown column db错误。


编辑:根据OP评论,您可以使用传统方法并在字段前加上数据透视表名称:

public function organizations()
{
    return $this->belongsToMany('Organization')
      ->withPivot('ContractStatus')
      ->withTimestamps()
      ->orderBy('PIVOT_TABLE.created_at', 'desc');
}
相关问题