CakePHP - 连接表格后对数据进行分页
CakePHP - Paginate data after joining tables
我在对连接 2 个表的数据进行分页时遇到问题。在我的数据库中,我有 2 个表:
产品:
- product_id
- product_name
价格:
- product_id
- product_price
2个表之间的关系是,一个产品可以有很多不同的价格(在很多商店)。我想显示产品列表并按最便宜的价格订购。所以,这就是我到目前为止所做的:
$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 排序的。如果我将 'order' 参数更改为 'product_name',分页有效...
在执行查找之前,使用虚拟字段将min_price
定义为MIN(Prices.product_price)
(如here所述)
$this->Product->virtualFields['min_price'] = 'MIN(Prices.product_price)';
然后find的字段数组简化为:
$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'
);
我在对连接 2 个表的数据进行分页时遇到问题。在我的数据库中,我有 2 个表:
产品:
- product_id
- product_name
价格:
- product_id
- product_price
2个表之间的关系是,一个产品可以有很多不同的价格(在很多商店)。我想显示产品列表并按最便宜的价格订购。所以,这就是我到目前为止所做的:
$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 排序的。如果我将 'order' 参数更改为 'product_name',分页有效...
在执行查找之前,使用虚拟字段将min_price
定义为MIN(Prices.product_price)
(如here所述)
$this->Product->virtualFields['min_price'] = 'MIN(Prices.product_price)';
然后find的字段数组简化为:
$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'
);