CakePHP - 分页和排序二级关联

标签 cakephp pagination cakephp-2.3

我知道这已被问到 100,000 次,但我几乎阅读了所有 100,000 条回复,但似乎没有一个与我所追求的相符。我已经尝试了所有可能的组合(显然不是),恐怕我在一些相对简单的事情上被击败了。这是我的第二个蛋糕项目,所以我绝不是专家。

个人资料-> 属于 -> 商店,商店 -> 属于 -> 地区,地区 -> HasMany -> 商店

公司简介 .php

class Profile extends AppModel {  
public $belongsTo = array(
            'Store' => array(
                'className' => 'Store',
                'foreignKey' => 'store_id'....

店铺 .php
class Store extends AppModel {
public $belongsTo = array(
        'Region' => array(
            'className' => 'Region',
            'foreignKey' => 'region_id'....

地区 .php
class Region extends AppModel {
public $hasMany = array(
        'Store' => array(
            'className' => 'Store',
            'foreignKey' => 'region_id'....

ProfileController .php
$this->Paginator->settings = array(
    'conditions' => array('Profile.job_title_id' => '1'),
    'contain' => array(
        'Store'=> array(
            'Region'
        )
    )
);
$UserArds = $this->Paginator->paginate('Profile');
$this->set(compact('UserArds'));

查看 .php
<th><?php echo $this->Paginator->sort('Region.name', 'Region'); ?></th>

我想要做的就是在使用分页器时能够按区域名称进行排序。无论我使用什么组合,我似乎都无法对 Region.name 进行排序。 order By所有其他 2 级深度关联都省略了子句,但在其他任何时候都可以正常工作(具有相同级别或 1 级)。

任何人都可以建议修复这个简单的错误吗?

最佳答案

查看 SQL 调试输出,正在使用单独的查询检索区域,这就是 Cakes ORM 当前的工作方式。

在您的情况下,有一个相对简单的解决方法。刚刚create a proper association on the fly ,例如 Profile belongsTo Region .

这是一个(未经测试的)示例,它添加了一个 belongsToforeignKey 的关联选项设置为 false为了禁用 ORM 的自动外键生成,这是必要的,否则它会寻找类似 Profile.region_id 的东西。 .请注意,因此 contain配置也要改!

$this->Profile->bindModel(array(
    'belongsTo' => array(
        'Region' => array(
            'foreignKey' => false,
            'conditions' => array('Region.id = Store.region_id')
        ),
    )
));

$this->Paginator->settings = array(
    'conditions' => array('Profile.job_title_id' => '1'),
    'contain' => array('Store', 'Region')
);

这应该会生成一个正确的查询,其中包含 stores以及 regions表,可以在 Region.name 上进行排序.请注意,结果数组会有所不同,Region不会嵌套在 Store ,一切都将被放置在同一级别,即:
Array
(
    [Profile] => Array
        (
            ....
        )

    [Store] => Array
        (
            ....

        )

    [Region] => Array
        (
            ....

        )
)

要么相应地修改 View 代码,要么在将检索到的数据传递给 View 之前对其进行转换。第三种选择是包含一个嵌套的 Regioncontain config,但是这会导致完全不必要的额外查询,因为数据已经通过主查询获取,所以我不建议这样做。

关于CakePHP - 分页和排序二级关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18958410/

相关文章:

cakephp - 如何在 cakephp 3 中运行所有插件的所有迁移?

cakephp - 如何处理完整性约束违规错误

javascript - 滑动轮播 - 分页未指向正确的位置

php - CakePHP. SQLSTATE[42S22] : Column not found: 1054 Unknown column 'CalendarsClassification.id' in 'field list'

mysql - 我们如何从 Cakephp 中的两个表中减去两列的总和

本地主机上的 cakephp css 和图像问题

python - 如何在非通用 View / View 集中使用分页?

laravel - 如何使用Laravel 5在Elasticsearch中分页

mysql - 如何在cakephp2中使用mysql函数

mysql - cakephp 分页顺序被忽略