2013-04-30 99 views
12

我有这个连接:在Laravel使用鲜明流利

Return DB::table('volunteer') 
      ->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id') 
      ->select(array('*','volunteer.id AS link_id')) 
      ->where('is_published', '=', 1) 

但勿庸置疑返回重复的记录,所以我尝试使用distinct()

Return DB::table('volunteer') 
      ->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id') 
      ->select(array('*','volunteer.id AS link_id')) 
         ->distinct() 
      ->where('is_published', '=', 1) 

,但我想在使用distinct()特定的单个字段,我可以轻松地在SQL中执行此操作。看起来distinct()不接受参数,即我不能说distinct('volunteer.id')

任何人都可以指出我如何删除我的重复记录?我敢打赌,这是我的另一个前额拍板。

+0

当然,我在这里完全是愚蠢的,需要添加' - > group_by('volunteer.id')'以及' - > distinct()'。 – 2013-04-30 18:07:24

+0

但包括' - > group_by('volunteer.id')'让我的分页链接消失!! ??? – 2013-04-30 18:20:05

+0

我相信Laravel 3有一段时间出现了分页和group_by的错误;我不知道它是否在Laravel 4中得到解决。 – 2013-05-01 08:16:00

回答

26

在我的项目我试着distinct()groupby()也和他们两个的工作:

//Distinct version. 
Company_Customer_Product::where('Company_id', '=', $companyid)->distinct()->get(array('Customer_id')); 
//Goup by version. 
Company_Customer_Product::where('Company_id', '=', $companyid)->groupby('Customer_id')->get(array('Customer_id')); 

据此,distinct()应该工作你的情况也一样,只是get()使用它:

Return DB::table('volunteer') 
    ->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id') 
    ->select(array('*','volunteer.id AS link_id')) 
    ->distinct() 
    ->where('is_published', '=', 1) 
    ->get(array('volunteer.id')); 

否则,当您使用groupby()时,您不需要distinct(),因此您可以使用:

Return DB::table('volunteer') 
    ->join('volunteer_volunteer_category', 'volunteer_volunteer_category.volunteer_id', '=', 'volunteer.id') 
    ->select(array('*','volunteer.id AS link_id')) 
    ->group_by('volunteer.id') 
    ->where('is_published', '=', 1) 
    ->get(array('volunteer.id'));