如何从数据库中检索数据时隐藏重复数据

时间:2019-03-10 18:26:50

标签: php mysql sql laravel-5 laravel-5.7

我具有此功能:

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();

我收到此错误:

enter image description here

当我删除groupBy部分时,它可以工作,但是像这样的重复数据 它返回这样的数据:

[{"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}]

谢谢。

1 个答案:

答案 0 :(得分:1)

使用此

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.id as user_id',
            'users.name as name',
            'group_user.user_id as id',
            'groups.name as groupname',
            'meetings.owned_by_id as meetings'
        )
        ->groupBy('user_id')
        ->get();

将config \ database.php更改为

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix' => '',
    'strict' => false, // must be false
    'engine' => null
],