2014-09-26 45 views
0

我有营造良好的CRM系统,在那里我与组织许多通过透视表

链接联系人在我接触模型的created_at领域的许多关系排序我:

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

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

我该怎么做?

回答

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'); 
} 
+0

我的OrderBy(“pivottablename.created_at”解决了这个问题,“说明” )。我不知道他们在表格字段的前缀也是 – moasking 2014-09-26 11:25:20

+0

是的,当然明确引用的字段是另一种选择。 – 2014-09-26 11:27:00