在Cakephp中有更好的方法来写这个:
$unread_orders = $this->Order->find('all', array('conditions' => array('Order.status' => 'unread') ));
$read_orders = $this->Order->find('all', array('conditions' => array('Order.status' => 'read') ));
$dispatched = $this->Order->find('all', array('conditions' => array('Order.status' => 'dispatched'), 'limit' => 5));
$canceled = $this->Order->find('all', array('conditions' => array('Order.status' => 'canceled'), 'limit' => 5));
调度和取消的项目有限制。
在一次调用数据库而不是4次调用中,似乎会有更有效的方法。
干杯。
答案 0 :(得分:2)
一种方法是做
$orders_read_unread = $this->Order->find('all', array('conditions' => array('OR' => array(array('Order.status' => 'unread'), array('Order.status' => 'read')))));
$orders_disp_cancel = $this->Order->find('all', array('conditions' => array('OR' => array(array('Order.status' => 'canceled'), array('Order.status' => 'dispatched'))), 'limit' => 5));
编辑:更新了查询。感谢Mark澄清。
答案 1 :(得分:0)
<?php
...
$orders_read_unread = $this->Order->find( 'all', array(
'conditions' => array( 'Order.status' => array( 'unread', 'read' )),
'group' => array( 'Order.status' ),
));
/**
* Use this if you need 5 of EITHER canceled OR dispatched order
* if you need 5 of EACH you need to break it into two queries.
*/
$orders_dispatched_canceled = $this->Order->find( 'all', array(
'conditions' => array( 'Order.status' => array( 'canceled', 'dispatched' )),
'group' => array( 'Order.status' ),
'limit' => 5
));
/**
* Use these if you need 5 of EACH dispatched AND canceled orders
*/
$orders_dispatched = $this->Order->find( 'all', array(
'conditions' => array( 'Order.status' => 'dispatched' ),
'group' => array( 'Order.status' ),
'limit' => 5
));
$orders_canceled = $this->Order->find( 'all', array(
'conditions' => array( 'Order.status' => 'canceled' ),
'group' => array( 'Order.status' ),
'limit' => 5
));
...
?>
在不必处理'OR'键语法的情况下,应该为您完成。它会产生效率稍低的IN ARRAY('..','..')语法,但保持php更清洁。
作为替代方案,您可以查看任何子查询 - 这对Cake来说很痛苦。本书有一个例子,通过数据源使用查询构建器将查询注入到普通蛋糕查找调用的条件数组中。
http://book.cakephp.org/view/1030/Complex-Find-Conditions
请记住,这两个发现应该在函数内部的模型中 - 您可以定义自定义查找类型,也可以直接从控制器调用模型函数。
http://www.pixelastic.com/blog/88:using-custom-find-and-paginate-methods-in-cakephp-1-3