當我在函式中傳遞值時,我想獲取祖先或子資料。
這是我來自 MySQL 表的資料。

如果我在我的函式中傳遞Document2的值,我想獲取祖先資料,例如,如果我傳遞Document2它將獲取Book2然后Book2將獲取Document1并且Document1將獲取Book1等等,然后與Profile1相同會得到Document0動態的。
這是我的代碼。
$binded = array('Document2');
$sources = [];
foreach ($binded as $document) {
$check = $this->db->where('binded',$document)
->get('binded_document');
$results = $check->result();
foreach($results as $key => $result){
array_push($sources, $result->source);
$ancestral = $this->db->where('binded',$result->source)
->get('binded_document');
$ancestrals = $ancestral->result();
foreach($ancestrals as $k => $r){
array_push($sources, $r->source);
}
}
}
我的代碼的問題是,如果函式中傳遞的值超過 2 個祖先,它將不會動態獲取祖先資料。
uj5u.com熱心網友回復:
DBFIDDLE
- 我確實選擇用
-.
WITH RECURSIVE cte AS (
SELECT
source as s,
CAST(Binded AS CHAR(1024)) as b,
1 as c
FROM table1 WHERE Binded='Document2'
UNION ALL
SELECT table1.source, CONCAT(cte.s,'-',cte.b), c 1
FROM cte
LEFT JOIN table1 ON table1.Binded = cte.s
WHERE c<10 AND NOT cte.s IS NULL
)
select b
from cte
where cte.s is null and NOT b is null
group by b
;
輸出:
| b |
|---|
| Document0-Profile1-Document2 |
| Book1-Document1-Book2-Document2 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/431251.html
