0
我想從我的CakePhp 2.x應用程序中的Orders表中得到結果列表,以按照離今天最近的日期排序。CakePHP 2 Paginate Order By最近日期
在通常的MySQL查詢我有過類似的與說的語法如下工作的東西:
ABS(DATEDIFF(Order.duedate, NOW()))
然而,在蛋糕,我不知道如何得到這樣的自定義查詢到PAGINATE助手裏工作。這是我可能需要在模型中的查找器查詢中設置的東西嗎?
這裏是控制器我現在有(設定爲沼澤標準降序排序)
public function index() {
$this->paginate = array(
'conditions' => array (
'Order.despatched' => array('Not Despatched' , 'Split Despatched')
),
'limit' => 25,
'order' => array('Order.duedate' => 'DESC')
);
$data = $this->paginate('Order');
$this->set('orders', $data);
}
編輯:從評論使用信息下面我添加了一個虛擬字段插入引起SQL錯誤的控制器。起初,我認爲這是由於模型內的關聯,試圖糾正這一點,我將virtualField添加到訂單模型中,並添加到相關賬戶模型的構造函數中。然而,這並沒有改變的部分斷裂的SQL。完整的SQL錯誤是:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS `Order__closestdate`, `Account`.`id`, `Account`.`company`, `Account`.`contac' at line 1
SQL Query: SELECT `Order`.`id`, `Order`.`order_id`, `Order`.`orderdate`,
`Order`.`duedate`, `Order`.`rework`, `Order`.`rework_notes`, `Order`.`comments`,
`Order`.`status`, `Order`.`customer`, `Order`.`last_edited`, `Order`.`value`,
`Order`.`quantity`, `Order`.`order_for`, `Order`.`warehouse`, `Order`.`haulier`,
`Order`.`terms`, `Order`.`type`, `Order`.`despatched`, `Order`.`despatched_date`,
`Order`.`invoiced`, `Order`.`invoice_date`, `Order`.`bookingref`,
`Order`.`purchaseref`, `Order`.`payment_due`, `Order`.`payment_status`,
`Order`.`payment_date`, (ABS(DATEDIFF(duedate, NOW())) AS `Order__closestdate`,
`Account`.`id`, `Account`.`company`, `Account`.`contact`, `Account`.`phone`,
`Account`.`email`, `Account`.`postcode`, `Account`.`created`, `Account`.`modified`,
`Account`.`customer`, `Account`.`address1`, `Account`.`address2`, `Account`.`town`,
`Account`.`county`, (ABS(DATEDIFF(duedate, NOW())) AS `Account__closestdate` FROM
`hunter_om`.`orders` AS `Order` LEFT JOIN `hunter_om`.`accounts` AS `Account` ON
(`Order`.`customer` = `Account`.`customer`) WHERE `Order`.`despatched` IN ('Not
Despatched', 'Split Despatched') ORDER BY (ABS(DATEDIFF(duedate, NOW())) DESC LIMIT 25
僅供參考模型中的代碼是:
//Order Model
public $virtualFields = array(
'closestdate' => 'ABS(DATEDIFF(duedate, NOW())'
);
//Account Model
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->virtualFields['closestdate'] = $this->Order->virtualFields['closestdate'];
}
任何幫助表示讚賞感謝。
感謝您的答覆你好,這個解決方案給我(ABS(DATEDIFF(交貨期,現在是一個SQL語法錯誤( )))AS'Order_closestdate'是罪魁禍首,我認爲這與模型中的關聯有關(根據cookbook,這會導致sql問題),但是我嘗試在模型中構造virtualField並且仍然出現錯誤。你有什麼想法嗎? – DevelopingTheWeb
你可以添加生成錯誤的查詢的完整SQL嗎?也許將它添加到你原來的問題中,因爲在commen中格式化t塊是有限的 – thaJeztah
嗨,我已經添加了額外的信息,原來的問題。 – DevelopingTheWeb