Very complex sql function => Cake ORM

I’m trying to convert a sql function into Cake’s ORM, but is having some problem with it. It’s divided into multiple queries using WITH, and I’m unsure of how to do this in Cake. Hope someone can help.

The SQL:

   WITH pns AS
    coalesce(p.ki_common_name, p.ek_common_name), AS pni,,
    CASE WHEN pno.ok IS NULL THEN false ELSE pno.ok END AS ok
   FROM ki.persons p
   INNER JOIN ki.person_names pn ON (pn.person_id =
   LEFT JOIN analysis.person_name_ok pno ON (pno.person_name_id =
   LEFT JOIN (SELECT (SELECT id FROM person_names WHERE person_id = ORDER BY id LIMIT 1) AS primid FROM persons p) prim ON (prim.primid =
   WHERE NOT IN (SELECT * FROM ki.verify_do_not_include())
     AND (EXISTS (SELECT * FROM ki.kimkat_department_persons WHERE username = p.ki_username AND active_affiliation)
       OR EXISTS (SELECT * FROM ki.research_affiliations WHERE person_id = AND active AND research_org))
     AND (include_ok OR pno.ok ISNULL OR pno.ok=false)
     AND prim.primid ISNULL
   selection AS
    SELECT id FROM pns WHERE NOT ok GROUP BY id HAVING count(*) >= x
   SELECT pns.* FROM pns INNER JOIN selection ON ( =
   ORDER BY, pns.pni;

This is my attempt so far at coding the ORM in Cake:

function getManyNamestrings(int $x, bool $include_ok): array {
    $sub1 = $this->find()
        ->select(['id' => 'id'])
        ->where(['person_id' => ''])

$sub2 = $this->find()
    ->select(['primid' => $sub1])
    ->from(['p' => 'persons']);

$sub3 = $this->find()
        'username' => 'p.ki_username',

$sub4 = $this->find()
        'person_id' => '',

$sub5 = $this->find()
        'pid' => '',
        'pname' => $this->find()->newExpr('COALESCE(p.ki_common_name, p.ek_common_name)'),
        'pnid' => '',
        'namestr' => '',
        'isok' => $this->find()->newExpr('CASE WHEN pno.ok IS NULL THEN false ELSE pno.ok END'),
    ->join(['pn' => ['table' => 'ki.person_names', 'type' => 'inner', 'conditions' => 'pn.person_id =']])
    ->join(['pno' => ['table' => 'analysis.person_name_ok', 'type' => 'left', 'conditions' => 'pno.person_name_id =']])
    ->join(['prim' => ['table' => $sub2, 'type' => 'left', 'conditions' => "prim.primid ="]])
        $this->find()->newExpr(' NOT IN (SELECT * FROM ki.verify_do_not_include())'),
        $this->find()->newExpr("(EXISTS ($sub3) OR EXISTS ($sub4))"),

   if (!$include_ok) {
       $sub5->where('(pno.ok ISNULL OR pno.ok=false)');

$sub6 = $this->find()
   ->select(['p' => $this->find()->func()->count('*')])
   ->where($this->find()->newExpr('NOT ok'))
   ->having(['p' >= $x]);

return $this->find()
    ->join(['table' => $sub6, 'type' => 'inner', 'conditions' => ' ='])
    ->order(', pns.pni')


If that query works, just use it with cakes pdo instance.