【问题标题】:CakePHP 3.x Contains GroupByCakePHP 3.x 包含 GroupBy
【发布时间】:2018-02-22 22:37:57
【问题描述】:

我正在尝试通过 contains -> 条件对关联表执行 GroupBy,但是出现以下错误...

错误:SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 'group = 'BrandUsers.user_id' AND BrandUsers.brand_id in (1,2,3,4,5,6))' 附近使用正确的语法

使用以下查询

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')])
);

【问题讨论】:

    标签: cakephp cakephp-3.x


    【解决方案1】:

    正如您所链接的问题的答案/cmets 中所述,没有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 关联,因为它们没有加入到主/父查询中。

    另见

    【讨论】:

      猜你喜欢
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2015-06-25
      • 2016-11-23
      • 2016-01-05
      相关资源
      最近更新 更多