2015-05-26 41 views
3

我正在將我的應用轉換爲cakephp 3.0,並且我無法找到在find方法中使用鄰居的替代方法。Cakephp中是否有鄰居的替代方案

我需要找到關聯表中的下一條記錄,鄰居是一個很好的方式來做到這一點。

//Open courses 
$options = [ 
    'conditions' => ['Employees.user_id' => 1, 'CoursesEmployees.completed' => false], 
    'limit' => 3, 
    'contain' => 'Employees' 
]; 
$recentOpen = $this->CoursesEmployees->find('all', $options)->toArray(); 

// get next module for each open course 
foreach ($recentOpen as $key => &$value) { 
    $currentModule = $value['CourseModule']['id']; 
    $neighbors = $this->CoursesEmployees->CourseModules->find(
     'neighbors', 
     ['field' => 'id', 'value' => $currentModule] 
    ); 
    $value['CourseModule']['next_module'] = $neighbors['next']['CourseModule']['name']; 
}; 

與代碼的另一個問題,我發現是$this->CoursesEmployees->find('all', $options)->toArray();彷彿回到一切CakePHP中使用複雜的陣列來查詢表,而不是實際結果就像我使用CakePHP 2.獲得我加入了->toArray()與建議3.0

回答

0

正如所解釋的here 沒有鄰居的CakePHP 3

找到方法,但如果你按照問題的流程,你會發現一個自定義的取景器來完成它,也許它會爲你工作。

+0

謝謝,我會尋找建立我自己的發現者的方法。至少它我知道沒有替代它。羞愧是有用的,看不出有理由放棄它。如果我沒有從'$ this-> CoursesEmployees-> find('all',$ options) - > toArray()獲得結果,你會有什麼想法嗎?'Cakephp 3在這個階段似乎沒有做這個查詢有沒有結果,不像2.0 –

+0

我不知道最後一個問題@KeithPower。事實上,我有一些同樣的問題,但我圍繞它。也許你可以嘗試另一種方式來做到這一點? ( '$ query = $ articles-> find() - > – Tzaoh

4

因爲我討厭「答案」,簡單地指向,你可能會或可能不會是今天能夠破譯半回答一個網址,但可以明天去,這是我更換自定義查找:

// In src/Models/Table/ExampleTable.php 
/** 
* Find neighbors method 
*/ 
public function findNeighbors(Query $query, array $options) { 
    $id = $options['id']; 
    $previous = $this->find() 
      ->select('id') 
      ->order(['id' => 'DESC']) 
      ->where(['id <' => $id]) 
      ->first(); 
    $next = $this->find() 
      ->select('id') 
      ->order(['id' => 'ASC']) 
      ->where(['id >' => $id]) 
      ->first(); 
    return ['prev' => $previous['id'], 'next' => $next['id']]; 
} 

簡單地在控制器中調用:

// In src/Controller/ExamplesController.php 
public function view($id = null) { 
    ... 
    $neighbors = $this->Examples->find('neighbors', ['id' => $id]); 
    .... 
} 
相關問題