简体   繁体   中英

CakePHP 3 Error: SQLSTATE[42000]: Syntax error or access violation: 1064

I'm getting this error:

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

Here is the SQL query which is giving this error:

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

I enabled quoteIdentifiers config\\app, but it leads to this new error:

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

where the query becomes:

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

I think it's taking the 'Col from Colleges as the keyword 'COL', but I'm not sure. How to fix this?

This is the CakePHP code which is generating the MySQL query:

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

You cannot use Colleges.* in a CakePHP ORM query (CakePHP 3.x). As you've discovered this creates incorrect SQL aliases like Colleges__* . Instead to select all columns of a table you need to pass a table object.

So you'd probably be wanting to do something like:-

->select($college_admins->Colleges)

Assuming Colleges is associated with your CollegeAdmins table.

You cannot alias colleges.*, since this refers to all columns within colleges table and aliases refer to a single column (or table or subquery). You need to list all fields within the colleges table and provide an alias for each of them, such as

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

There is not syntax in sql to provide alias such way. What you may try to do is to access the metadata returned by mysql in php to retrieve the table name for each field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM