CakePHP 3.x 包含 GroupBy

CakePHP 3.x Contains GroupBy

我试图通过包含 -> 条件对关联的 table 执行 GroupBy,但是我收到以下错误...

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group = 'BrandUsers.user_id' AND BrandUsers.brand_id in (1,2,3,4,5,6))' at line 1

使用以下查询

SELECT
    BrandUsers.id AS `BrandUsers__id`,
    BrandUsers.user_id AS `BrandUsers__user_id`,
    BrandUsers.brand_id AS `BrandUsers__brand_id`,
    Users.id AS `Users__id`,
    Users.username AS `Users__username`,
    Users.email AS `Users__email`,
    Users.password AS `Users__password`,
    Users.first_name AS `Users__first_name`,
    Users.last_name AS `Users__last_name`,
    Users.token AS `Users__token`,
    Users.token_expires AS `Users__token_expires`,
    Users.api_token AS `Users__api_token`,
    Users.activation_date AS `Users__activation_date`,
    Users.secret AS `Users__secret`,
    Users.secret_verified AS `Users__secret_verified`,
    Users.tos_date AS `Users__tos_date`,
    Users.active AS `Users__active`,
    Users.is_superuser AS `Users__is_superuser`,
    Users.role AS `Users__role`,
    Users.created AS `Users__created`,
    Users.modified AS `Users__modified` 
FROM
    brand_users BrandUsers 
    INNER JOIN
        users Users 
        ON Users.id = 
        (
            BrandUsers.user_id
        )
WHERE
    (
        group = :c0 
        AND BrandUsers.brand_id in 
        (
            :c1,
            :c2,
            :c3,
            :c4,
            :c5,
            :c6
        )
    )

我已经查看了以下链接,但上面的错误仍然存​​在

这是我的代码

$this->paginate = [
    'contain' => [
        'BrandUsers' => [
            'conditions' => [
                'group' => 'BrandUsers.user_id'
            ]
        ],
        'BrandUsers.Users'
    ]
];

$brands = $this->paginate(
    $this->Brands
        ->find('all')
        ->where(['Brands.user_id' => $this->Auth->user('id')])
);

正如在您链接的问题的 answers/comments 中提到的,没有 group 包含选项,对于 CakePHP 2.x 和 3.x,如果有这样的选项,你会把它放错了,因为你已经将它嵌套在 conditions 选项中,因此它被编译到查询 WHERE 子句中。

如果您需要修改用于动态获取包含的查询,那么您可以例如传递一个从其他查询构建器方法中获知的可调用对象:

'BrandUsers' => function (\Cake\ORM\Query $query) {
    return $query->group('BrandUsers.user_id');
}

或使用 finder 选项指向一个查找器,相应地修改传递的查询:

'BrandUsers' => [
    'finder' => 'groupedByUser'
]

请注意,分组仅适用于 HasManyBelongsToMany 关联,因为它们未加入 main/parent 查询。

另见