作者olctw (olc.tw)
看板PHP
標題Re: [CakePHP] 請問 recursive
時間Tue May 19 11:08:23 2009
簡單的說, recursive 讓你控制程式自動取得關聯資料的深度,舉個簡單的例子:
國家 -> 縣市 -> 鄉鎮市區 -> 里 -> 鄰
在上面關聯中,如果從鄉鎮市區取資料 $this->鄉鎮市區->find('first');
-1 只有取得 鄉鎮市區
0 取得 鄉鎮市區+縣市
1 取得 鄉鎮市區+縣市+里
2 取得上面 5 個關聯資料
>2 繼續往外擴展
方便,但是沒有效率,請愛用 Containable Behavior ;)
---
kiang
※ 引述《bobju (寶貝豬)》之銘言:
: 官網上面還有這麼一段有關recursive的描述:
: http://book.cakephp.org/view/439/recursive
: 簡單講, 它是用來控制find()要找的資料模型(model)對外關聯的層數. 從它舉的
: 例子來看:
: -1 代表僅限於model本身, 不對外做join的動作.
: 0 代表本身, 以及其所belongs to 的model.
: 1 代表本身, 以及其所belongs to 的model, 還有其所have many(has one)的model
: 2 代表1 所包含的範圍, 並更深入下一層的model.
: Imagine your application features Groups which belong to a domain and have
: many Users which in turn have many Articles.
: 就以 groups, domain, users, articles 的關聯來舉例, 大概就抓得到recursive
: 在這裏的用途.
: 以下補充個人經驗:
: 我們在用cake 做快速塑模時, 就已先把model之間的關聯都建立好了, 當然也包括
: primary key與foreign key的聯結. 而後續在程式當中要用find()函式來撈資料
: 時, 也必須手動地在$fields當中加入foreign key.
: 當然底下那段話的意思也能抓了個8成準了.
: ※ 引述《HuangJC (吹笛牧童)》之銘言:
: : 同事的程式中有這一句
: : $this->User->findByEmail($email, null, null, -1)
: : 經翻查 findBy 的章節,help 是這樣寫的
: : findBy<fieldName>(string $value)
: : 難怪我上次學習 Cake 時,大家看不懂這是什麼
: : 但如果去 trace source code,會發現它真的能動!
: : (X啦,超過文件的規格可以視為 side effect 呀!!)
: : 好吧,我就繼續 trace,發現 recursive 其實在別的章節找得到文件
: : 比如在 findAll
: : findAll(string $conditions, array $fields, string $order, int $limit, int
: : $page, int $recursive)
: : findAll has been deprecated, use find('all') instead.
: : 這句有趣吧,help 說 findAll 已經不建議使用了
: : 但是 CakePHP 內部還是用它 implement 的,用得很爽
: : 換言之就是 'UnDocument' (應該說文件不推薦才對,因為文件還是把它列出了)
: : 那什麼是 recursive 呢?
: : Setting the $recursive parameter to an integer forces findAll() to fetch data
: : according to the behavior described in the Model Attributes $recursive
: : section outlined earlier. Do not forget to manually add the required foreign
: : key columns to the $fields array as described there.
: : 以上,整段翻譯對我有些困難 ~^_^~
: : 麻煩講解了
: : 謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.135.155.104
推 HuangJC :照您的描述並不對稱,或者您只講概念罷了 05/19 11:28
→ HuangJC :0 多取得向左一個,1多向右一個,這是我所謂不對稱 05/19 11:29
→ HuangJC :2 取得再向左及向右一個,而不是只有再向左一個?那我 05/19 11:30
→ HuangJC :如果很計較細節,真的得 trace 更多 code 了 05/19 11:30
→ HuangJC :我同事則是說,早就放棄而自己寫 SQL 了;為了效率 05/19 11:30
→ aquarianboy :江哥也加入ptt了 :) 05/19 12:30
→ olctw :設定數字本身沒有直接的邏輯,那是原始開發者的邏輯 05/20 08:11
→ olctw :為了效率當然要自己寫 SQL ,但如果需要產生一個雛型 05/20 08:11
→ olctw :你就知道它的好處了 ;) 05/20 08:12
→ olctw :@aquarianboy我其實很早以前有註冊,但是密碼忘了... 05/20 08:13
推 HuangJC :樓上那好像是噗浪的語法 ~^_^~ 05/20 12:07
推 chph :原po是台灣PHP聯盟站長~推 05/20 23:46
→ kylekai :Kiang 來了阿... 05/21 15:08