按列分组(Doctrine 2 + Mysql 5.7)

时间:2016-06-20 13:05:50

标签: symfony doctrine

我正在尝试对用户和路径进行分组,并根据创建的列限制每个用户的1个路径。下面是我的结果,问题是user_id(1)因路径不同而被发现两次

RESULT

{
    "user_id": 1,
    "lastname": "Short",
    "firstname": "Admin",
    **"path": "/dashboard"**
},
{
    "user_id": 1,
    "lastname": "Short",
    "firstname": "Admin",
    **"path": "/works"**
},
{
    "user_id": 2,
    "lastname": "Administrator",
    "firstname": "John",
    "path": "/dashboard"
}

实体

user => | id | firstname | lastname | profile_image | created

beat => | id | user_id(rel) | created | path

QueryBuilder(Symfony)

        return $this
        ->createQueryBuilder('b')
        ->select('
            u.id as user_id,
            u.lastname,
            u.firstname,
            u.profile_image,
            b.path
        ')
        ->join('b.user', 'u')
        ->groupBy('u.id, b.path')
        ->getQuery()
        ->getArrayResult();

1 个答案:

答案 0 :(得分:1)

如果您只想获取每个用户一次,那么使用DISTINCT(u.id) AS user_id就可以了。如果你想坚持使用dql ->select('u.id as user_id)->distinct()