如何隐藏重复数据Laravel

时间:2019-03-07 10:26:37

标签: php mysql laravel

你好我有此功能

 public function readData(){
    $TableB1 = \DB::table('users')
    ->join('group_user', 'users.id', '=', 'group_user.user_id')
    ->join('groups', 'groups.id', '=', 'group_user.group_id')
    ->join('meetings', 'users.id', '=', 'meetings.owned_by_id')
    ->select(
        'users.name as name',
        'group_user.user_id as id',
        'groups.name as groupname',
        'meetings.owned_by_id as meetings'
    )
    ->get();


    return $TableB1;

   }

它返回这样的数据:

[{"name":"Mohamed Adel","id":6,"groupname":"Team Mohamed","meetings":6},{"name":"Mohamed Adel","id":6,"groupname":"Team Mohamed","meetings":6},{"name":"Norman Osborn","id":2,"groupname":"Team Mohamed","meetings":2},{"name":"Harry Osborn","id":3,"groupname":"Team Harry","meetings":3}]

您可以看到我有2个Mohamed Adel对象如何隐藏它们
或如何正确查询,这样我就不会每次都重复

我编辑了功能

public function readData(){
$TableB1 = \DB::table('users')
->join('group_user', 'users.id', '=', 'group_user.user_id')
->join('groups', 'groups.id', '=', 'group_user.group_id')
->join('meetings', 'users.id', '=', 'meetings.owned_by_id')
->select(
    'users.name as name',
    'group_user.user_id as id',
    'groups.name as groupname',
    'meetings.owned_by_id as meetings'
)
->groupBy('users.id')
->get();

我收到此错误:https://ibb.co/FqPd1Wz

2 个答案:

答案 0 :(得分:1)

您需要使用groupBy这样的方法:

->groupBy('group_user.user_id')

请参阅此文档链接Laravel Query Builder Group By

答案 1 :(得分:1)

您可以简单地将groupBy与查询生成器一起使用

    public function readData()
    {
        $TableB1 = \DB::table('users')
        ->join('group_user', 'users.id', '=', 'group_user.user_id')
        ->join('groups', 'groups.id', '=', 'group_user.group_id')
        ->join('meetings', 'users.id', '=', 'meetings.owned_by_id')
        ->select(
            'users.name as name',
            'group_user.user_id as id',
            'groups.name as groupname',
            'meetings.owned_by_id as meetings'
        )
        ->groupBy('users.name')
        ->get();
        return $TableB1;
    }

您可以了解有关groupBy here

的更多信息