2012-08-10 174 views
2

我有幾個嵌套模型,我試圖在CakePHP中使用Containable行爲加載。 大部分工作正常。Containsable嵌套模型

然而,有一個hasMany關係1個模型只返回1個對象:

$article = $this->News->find('first',array(
    'conditions'=>array('News.id'=>$id), 
    'contain' => array(
     'Newslayout', 
     'Newspicture'=> array(
      'NewspicturesProduct' => array(
       'Product' => array(
        'Brand', 
        'Category' 
       ) 
     ))) 
    )); 

只被加載一次的對象是關係Newspicture hasMany NewspicturesProduct 當我登錄查詢,我得到如下:

SELECT `NewspicturesProduct`.`id`, `NewspicturesProduct`.`x`, `NewspicturesProduct`.`y`, `NewspicturesProduct`.`product_id`, `NewspicturesProduct`.`newspicture_id`, `NewspicturesProduct`.`w`, `NewspicturesProduct`.`h` FROM `edclondon`.`newspictures_products` AS `NewspicturesProduct` WHERE `NewspicturesProduct`.`newspicture_id` = 3 

哪給了我3結果phpMyAdmin。但只有1 CakePHP的調試:

'Newspicture' => array(
     (int) 0 => array(
      'id' => '3', 
      'news_id' => '2', 
      'newspicture_file_path' => '5022443f-ddf8-4115-ae57-618e9d60b047.jpg', 
      'newspicture_file_size' => '1232546', 
      'order' => null, 
      'NewspicturesProduct' => array(
       'id' => '1', 
       'x' => '0.180664', 
       'y' => '0.295312', 
       'product_id' => '3', 
       'newspicture_id' => '3', 
       'w' => '0.286133', 
       'h' => '0.478125', 
       'Product' => array(
        'id' => '3', 
        //.... 
        'Brand' => array(
         'id' => '6', 
         //... 
        ), 
        'Category' => array(
         'id' => '6', 
         //.... 
        ) 
       ) 
      ) 
     ) 

檢索Newspictures對象,而然後檢索News對象時,我得到的所有3個NewspicturesProduct對象。

回答

0

在我看來,那相應的表現,你應該查詢代碼:

$article = $this->News->find('first',array(
'contain' => array(
    'Newslayout', 
    'Newspicture'=> array(
     'NewspicturesProduct' => array(
      'conditions'=>array('NewspicturesProduct.newspicture_id'=>'3') 
      'Product' => array(
       'Brand', 
       'Category' 
      ) 
    ))) 
)); 

而不是你給了一個...

+0

但你怎麼能知道'Newspicture.id'爲您回覆您檢索'News.id' – 2012-08-13 10:14:21

-1

看來你需要從NewspicturesProduct 3條記錄。如果那麼你可以嘗試:

$article = $this->News->find('first',array(
'contain' => array(
    'Newslayout', 
    'Newspicture'=> array(
     'NewspicturesProduct' => array(
      'conditions'=>array(
          'limit'=> 3 
         ), 
      'Product' => array(
       'Brand', 
       'Category' 
      ) 
    ))) 
)); 
+0

由於在相同的查詢,但是我有3個做相應記錄。但問題是我只得到1.沒有那麼多,我不想那麼多3,而是我想要更多1 – 2012-08-13 10:12:57