【问题标题】:CakePHP - Paginate data after joining tablesCakePHP - 加入表格后对数据进行分页
【发布时间】:2015-04-17 09:54:59
【问题描述】:

我在对连接 2 个表的数据进行分页时遇到问题。在我的数据库中,我有 2 个表:

产品:

  • product_id
  • 产品名称

价格:

  • product_id
  • product_price

两个表之间的关系是,一个产品可以有许多不同的价格(在许多商店)。我想显示产品列表并以最便宜的价格订购它们。所以,这就是我到目前为止所做的:

        $this->paginate = array(
            'joins' => array(
                    array(
                            'table' => 'price',
                            'alias' => 'Price',
                            'conditions' => array(
                                    'Product.product_id = Price.product_id'
                            )
                    )
            ),
            'fields' => array(
                    'Product.product_id',
                    'Product.product_name',
                    'MIN(Prices.product_price) AS min_price'
            ),
            'order' => array('min_price' => 'ASC'),
            'limit' => 10,
            'group' => 'Product.product_id'
        );

这是加入后返回的数据:

[Product] => Array
       (
            [product_id] => 1
            [product_name] => iPhone 6 Plus 64GB
       )

[0] => Array
       (
            [min_price] => 20290000
       )

但列表不能按新字段“min_price”排序。它是按 id 排序的。如果我将“订单”参数更改为“产品名称”,则分页工作......

【问题讨论】:

  • CakePHp 中的命名约定希望表的 ID 被命名为“id”。
  • @James 好的,谢谢你的提醒:D

标签: mysql cakephp pagination


【解决方案1】:

在执行查找之前,使用虚拟字段将min_price 定义为MIN(Prices.product_price)(如here 所述)

$this->Product->virtualFields['min_price'] = 'MIN(Prices.product_price)';

那么find的field数组就简化为:

    $this->paginate = array(
        'joins' => array(
                array(
                        'table' => 'price',
                        'alias' => 'Price',
                        'conditions' => array(
                                'Product.product_id = Price.product_id'
                        )
                )
        ),
        'fields' => array(
                'Product.product_id',
                'Product.product_name',
                'min_price'
        ),
        'order' => array('min_price' => 'ASC'),
        'limit' => 10,
        'group' => 'Product.product_id'
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    相关资源
    最近更新 更多