I’m trying to load articles from our database using the following code:
$articles = $this->Articles->find('all',['order' => ['created' => 'DESC']])->contain(['Tags','Users']);
This, however, throws the error:
Integrity constraint violation: 1052 Column 'created' in order clause is ambiguous.
This is the SQL output I get:
SELECT Articles.id AS `Articles__id`, Articles.user_id AS `Articles__user_id`, Articles.title AS `Articles__title`, Articles.slug AS `Articles__slug`, Articles.body AS `Articles__body`, Articles.published AS `Articles__published`, Articles.created AS `Articles__created`, Articles.modified AS `Articles__modified`, Users.id AS `Users__id`, Users.username AS `Users__username`, Users.email AS `Users__email`, Users.password AS `Users__password`, Users.created AS `Users__created` FROM articles Articles INNER JOIN users Users ON Users.id = (Articles.user_id) ORDER BY created DESC
This error makes no sense to me, as when I remove the
Users from the content (so it will be
->contain(['Tags'])), it works without issues.
Simply removing the
,['order' => ['created' => 'DESC']] from the
find() does also get rid of the error, however, when I do that it will get the items in the wrong order.
Any clues on how to fix this?
EDIT: literally a few seconds after posting this I found the solution:
['created' => 'DESC'] with
['Articles.created' => 'DESC']