我试图通过包含 - >在关联的表上进行GroupBy条件,但我收到以下错误...
错误:SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册,以便在' group =' BrandUsers.user_id'附近使用正确的语法。 AND BrandUsers.brand_id in(1,2,3,4,5,6))'在第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')])
);
答案 0 :(得分:1)
正如你所链接的问题的答案/评论中所提到的,对于包含没有group
选项,对于CakePHP 2.x和3.x都是如此,如果有的话你将它放错了的一个选项,因为你已经将它嵌套在conditions
选项中,因此它被编译成查询WHERE
子句。
如果您需要动态修改用于获取包含的查询,那么您可以例如传递其他查询构建器方法中已知的可调用对象:
'BrandUsers' => function (\Cake\ORM\Query $query) {
return $query->group('BrandUsers.user_id');
}
或使用finder
选项指向相应修改传递的查询的查找程序:
'BrandUsers' => [
'finder' => 'groupedByUser'
]
应该注意的是,分组仅适用于HasMany
和BelongsToMany
关联,因为它们未加入主/父查询。
另见