【问题标题】:CakePHP 3 Error: SQLSTATE[42000]: Syntax error or access violation: 1064CakePHP 3 错误:SQLSTATE [42000]:语法错误或访问冲突:1064
【发布时间】:2016-02-10 14:56:57
【问题描述】:

我收到此错误:

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'AS `Colleges__*` FROM college_admins CollegeAdmins LEFT JOIN colleges Colleges O' at line 1

这是给出此错误的 SQL 查询:

SELECT Colleges.* AS `Colleges__*` FROM college_admins CollegeAdmins LEFT JOIN colleges Colleges ON Colleges.id = (CollegeAdmins.college_id) WHERE CollegeAdmins.user_id = :c0 LIMIT 20 OFFSET 0

我启用了quoteIdentifiers config\app,但它导致了这个新错误:

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'AS `Colleges__*` FROM `college_admins` `CollegeAdmins` LEFT JOIN `colleges` `Col' at line 1

查询变为:

SELECT `Colleges`.* AS `Colleges__*` FROM `college_admins` `CollegeAdmins` LEFT JOIN `colleges` `Colleges` ON `Colleges`.`id` = (`CollegeAdmins`.`college_id`) WHERE `CollegeAdmins`.`user_id` = :c0 LIMIT 20 OFFSET 0

我认为它将“Col from Colleges”作为关键字“COL”,但我不确定。如何解决这个问题?

这是生成 MySQL 查询的 CakePHP 代码:

return $college_admins->find()
    ->select(['Colleges.*'])
    ->leftJoinWith('Colleges')
    ->where(['CollegeAdmins.user_id' => $userId]);

【问题讨论】:

    标签: php mysql cakephp cakephp-3.x


    【解决方案1】:

    您不能在 CakePHP ORM 查询 (CakePHP 3.x) 中使用 Colleges.*。正如您所发现的,这会创建不正确的 SQL 别名,例如 Colleges__*。而不是选择表格的所有列,您需要传递一个表格对象。

    所以你可能想做这样的事情:-

    ->select($college_admins->Colleges)
    

    假设Colleges 与您的CollegeAdmins 表相关联。

    【讨论】:

    • 学院与 CollegeAdmins 相关联。你的解决方案也有效。它消除了错误。谢谢。但是您的解决方案和上面的解决方案都显示了带有空白值的行。我已将其发布在此处的一个单独问题中。如果您能提供帮助,请务必查看:stackoverflow.com/questions/35321261/…
    【解决方案2】:

    您不能给大学起别名。*,因为这指的是大学表中的所有列,而别名指的是单个列(或表或子查询)。您需要列出 Colleges 表中的所有字段,并为每个字段提供别名,例如

    select colleges.ig as colleges_id, colleges.field1 as colleges_field1, ...
    

    sql 中没有提供这种别名的语法。您可以尝试在 php 中访问 mysql 返回的元数据以检索每个字段的表名。

    【讨论】:

    • 好的。那解决了它。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 2014-01-14
    • 2013-12-02
    相关资源
    最近更新 更多