从数据库中动态获取祖先数据

Get the ancestral data from database dynamically

我想在函数中传递值时获取祖先或子数据。

这是我来自 MySQL table 的数据。

如果我在函数中传递 Document2 的值,我想获取祖先数据,例如,如果我传递 Document2它会得到 Book2 然后 Book2 会得到 Document1Document1 将得到 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 个祖先数据,它不会动态获取祖先数据。

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