2013-09-21 40 views
0

花了幾個小時爲以下問題找到解決方案後,我希望您能幫助我。Cakephp通過關聯模型查找訂單

我有兩個表:

Event hasmany Appointments and Appointment belongsto Event 

現在我在EventsController執行:

$this->Event->find('all') 

現在我要訂購的約會活動。因此,具有最早約會的事件首先在數組中,等等。我嘗試了很多方法,包含可加入,加入,分組,子選擇但沒有任何作用。

要執行$this->Event->Appointment上的查找('all')不是一個解決方案,因爲我希望每個事件都只有一個。

編輯#1: 我唯一的解決辦法,到目前爲止是 $事件= $這個 - >事件 - >找到( '所有',陣列( '加入'=>陣列( 陣列( '表'= >'(SELECT event_id,MIN(start)start FROM appointmentments GROUP BY event_id)', 'alias'=>'Appointment', 'type'=>'LEFT', 'conditions'=> array( 'Event .id = Appointment.event_id' ) ) ), 'order'=> array( 'Appointment.start ASC' ) ));

但這不是最好的解決方案!

回答

0

一種選擇是創建表示最早預約日期虛擬領域,您可以通過

排序在你的事件模型將這個:

function __construct($id = false, $table = null, $ds = null) { 
    $this->virtualFields['firstappt'] = 'SELECT MIN(Appointment.created) FROM appointments AS Appointment WHERE Appointment.event_id = Event.id'; 
    parent::__construct($id, $table, $ds); 
} 

您應該能夠在使用該代碼的控制器:

$this->Event->find('all',array('order' => array('firstappt'))); 
+0

這就像一個魅力!謝謝! –