Cakephp 3.x Sorting of another model is not working

十年热恋 提交于 2019-12-05 04:35:15

You just have to use this:

$this->paginate = [
    'sortWhitelist'=>['Roles.name']
];

UsersController.php

 $this->paginate = [
            'contain' => ['Roles'],
            'conditions' => [
                'Users.user_type <>' => 1
            ],
            'order' => ['Users.role_id' => 'ASC']
        ];

Use 'order' => ['Models.field' => 'ASC/DESC']

(I would add a comment to you question but I don't have enough reputation points.)

I am having the same issue.

This is happening because of the way containable behavior works. When CakePHP gets all the roles for an associated user, it issues a separate query (instead of using a join on the main query). Then it puts it all together in a nice object to use. Take a look at the sql in debug kit.

When you ask it to sort by role name, it can't because the table Roles is nowhere to be found in the main query. I am guessing you getting an error like this:

Error: SQLSTATE[HY000]: General error: 1 no such column: Roles.name

To make this work, you're going to have to figure out how to join the Roles table to the Users table in the main query for this to work. This is also why it works the other way. If the Users table belonged to the Roles table you wouldn't have this issue because the Roles table would be joined in the main query.

Another way to make it work could be to use the Roles model for the main query. But if your user's table has other hasMany associations that you want to sort by, this isn't going to work. (Which is my case.)

I've just started getting into CakePHP 3, so I really don't have an concrete answer at this point, but I hope this points you in the right direction.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!