2016-10-03 208 views
0

我试图获取与特定列表相关的所有ID,但我的查询只返回表中的第一个相关ID,而不是其他相关ID。Laravel:查询只获取一个相关的ID

List  | id | person_id | name  | description 
      | 1 | 10  | Test List | null 

List_Ref | id | list_id | data_id 
      | 1 | 1   | 100 
      | 2 | 1   | 101 

查询

$lists = DB::table('List') 
    ->leftJoin('List_Ref', 'List_Ref.list.id', '=', 'List.id') 
    ->select('List.id', 'List.name', 'List_Ref.data_id') 
    ->where('person_id', Auth::user()->person_id) 
    ->groupBy('List.id') 
    ->orderBy('List.id') 
    ->get(); 

结果(Laravel模具和转储)

#items: array:1 [ 
    0 => { 
    "id"  : 1 
    "name" : "Test List" 
    "data_id" " 100 
    } 
] 

我WOU ld喜欢产生如下结果

#items: array:1 [ 
    0 => { 
    "id"  : 1 
    "name" : "Test List" 
    "data_id" => { 
     "id" : 100 
     "id" : 101 
    } 
    } 
] 
+0

您是否正在尝试替换get() - > all() –

+0

如果您删除了group by,您将获得所需的所有结果。 –

+0

@MubasharAbbas我需要将所有'data_id'分组到一个列表 –

回答

0

如果您想获得可用的分组项目,请不要在构建查询时使用group by。

这样做:

$lists = DB::table('List') 
    ->leftJoin('List_Ref', 'List_Ref.list.id', '=', 'List.id') 
    ->select('List.id', 'List.name', 'List_Ref.data_id') 
    ->where('person_id', Auth::user()->person_id) 
    ->get(); 

$lists->groupBy('List.id')->orderBy('List.id'); 

使用laravel收集的GROUPBY和ORDERBY方法来获得分组的项目。希望它可以帮助你!

+0

更好谢谢你。这工作100%,而不必更改所有的代码。做得好 –

0

我不知道laravel,但你正在做一个从“List”到“List_Ref”的左连接。 因此,Talbe列表中的每个条目都将与List_Ref的一个条目匹配。

尝试完全加入。

0

不要使用groupBy('List.id')它会根据List表&的ID对数据进行分组总是只返回单个数据。

+0

谢谢。我现在明白了。当我删除'groupBy()'它显示了我的2个数组项目与伟大的ID。但我想分组所有的ID与列表相关。 in 1 array –

+0

我不是laravel人,但是对于那种情况,查询应该是:select group_concat(List_Ref.id)ids,blah ... blah ... group by List.id –

+0

你可以使用'whereRaw'来实现某些东西像上面那样。 ' - > whereRaw('GROUP_CONCAT(List_Red.id)')' – ash