2016-02-28 78 views
2

我需要找到具有相同作者的文章如何使用CakePHP中的匹配()找到具有共同父項的實體?

這裏給定列表中的所有的文章是我的自定義finder方法:

public function findSimilar(Query $query, array $options) 
    { 
     if (empty($options['idList'])) { 
      throw new Exception('idList is not populated'); 
     } 
     // We are given a list of article IDs 
     $idList = $options['idList']; 

     return $query->matching('Authors', function ($q) use ($idList) { 
      return $q->matching('Articles', function ($q2) use ($idList) { 
       return $q2->where(['Articles.id IN' => $idList]); 
      }); 
     }); 
    } 

不幸的是我收到以下錯誤消息: PDOException:SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'Articles' 我究竟做錯了什麼?

回答

5

有相當嵌套匹配有一些限制,這可能是其中之一。我無法分辨這是否是一個錯誤,因此您可能需要檢查issues on GitHub並最終提交一份新文件以供澄清。從文檔

引用:

[...]虛線相符路徑應當超過嵌套匹配(使用)調用[...]

Cookbook > Database Access & ORM > Retrieving Data & Results Sets > Filtering by Associated Data

在任何一種情況下,使用點符號代替嵌套應該解決問題,即

return $query->matching('Authors.Articles', function ($q) use ($idList) { 
    return $q->where(['Articles.id IN' => $idList]); 
}); 

如果你想也匹配Authors,你可以堆疊的匹配,就像

return $query 
    ->matching('Authors', function ($q) { 
     return $q->where(['Authors.foo' => 'bar']); 
    }) 
    ->matching('Authors.Articles', function ($q) use ($idList) { 
     return $q->where(['Articles.id IN' => $idList]); 
    }); 
2

如果是的hasMany關係,我們可以做到這一點很容易地:

return $query->where([ 
    'Articles.author_id IN' => $this->find() 
     ->select(['Articles.author_id']) 
     ->where(['Articles.id IN' => $idList]) 
]); 

//由於jose_zap在CakePHP的IRC通道

相關問題