2011-12-08 17 views
2

有沒有在cakephp使用ORM獲取屬於特定子項目的項目的方法。例如,我要獲取特定評論記錄的相關郵政記錄。cakephp如何找到屬於編號

這是我的評價模型:

var $belongsTo = array(
    'Post' => array(
     'className' => 'Post', 
     'foreignKey' => 'post_id', 
     'conditions' => '', 
     'fields' => '', 
     'order' => '' 
    ) 
); 

我想這一點,但它拉回來每一個崗位,即使是那些沒有我查詢反對意見:

$this->Post->contain('Comment'); 
$results = $this->Post->find('all', array(
    'contain' => array(
     'Comment' => array(
      'conditions' => array(
       'id' => 15 
      ) 
     ) 
))); 

任何其他方式來做到這一點?

回答

0

您確定不必在您的條件中指定模型?

例如:

$this->Post->contain('Comment'); 
$results = $this->Post->find('all', array(
    'contain' => array(
     'Comment' => array(
      'conditions' => array(
       'Comment.id' => 15 
      ) 
     ) 
))); 
+0

它工作瓦特沒有指定表名稱,問題是它拉回其他帖子以及不包含評論,他們只是有一個空白數組作爲評論。不過,我希望它只回拉包含評論的帖子。我可以使用以下方法修復數組:foreach($ results as $ key => $ value){ if(empty($ value ['Comment'])){ unset($ results [$ key]); } }但想要在查詢中做到這一點,爲了優化的緣故 – user781861

+0

我想不出一種辦法來做到這一點,而不是抓住太多並過濾掉它。事實上,我認爲如果你確實找到了一種方法來指定這些條件,蛋糕可能仍然會查詢一切,然後將其過濾掉。您可能必須爲此執行SQL查詢。 – swiecki

0

我的研究使我這個帖子就這個問題與包括: http://nuts-and-bolts-of-cakephp.com/2008/07/17/forcing-an-sql-join-in-cakephp/

所以我最終溶液如下:

$this->Post->unbindModel(array('hasMany' => array('Comment'))); 

    $results = $this->Post->bindModel(array('hasOne' => array(
      'Comment' => array(
       'foreignKey' => false, 
       'conditions' => array('Comment.post_id = Post.id')) 
     ))); 

    $results = $this->Post->find('all', array(
       'conditions' => array(
        'Comment.id' => 10 
       ))); 

不漂亮但得到的工作:)