2014-02-20 45 views
0

相關的表單項我有一個Item模型,它具有以下關聯:加入基於分鐘場

public $hasOne = array(
    'Project' => array(
     'className' => 'Project', 
     'foreignKey' => 'item_id' 
    ) 
); 
public $hasMany = array(
    'ItemPic' => array(
     'className' => 'ItemPic', 
     'foreignKey' => 'item_id', 
     'dependent' => false 
    ) 
); 

我想自定義數據的Item不同的看法。這似乎是CakePHP的自動包括Project數據(也許是因爲它是hasOne?),不包括ItemPic數據。在index我真的不想要Project數據...但是,我確實需要ItemPic數據。對於每個Item記錄拉,我想單個ItemPic記錄加入它。這ItemPic應該基本上是ItemPic.item_id = Item.idORDER BY ItemPic.rank LIMIT 1

這樣做的目的基本上是這樣,在指數我可以顯示項目的列表,並與每個項目相關聯的圖片。我想所有的viewProject數據沿圖像的單個Item,但不在列表/索引。

有人告訴我,我可以用containable這樣的:

// In the model 
public $actsAs = array('Containable'); 

// In the controller 
$this->paginate = array(
    'conditions' => $conditions, 
    'contain' => array(
     'ItemPic' => array(
      'fields' => array('file_name'), 
      'order' => 'rank', 
      'limit' => 1 
     ) 
    ) 
); 

以上實際工作如何我想......不過,我還被告知,這樣做會導致額外的查詢中跑了每單我Item ...我覺得我應該避免。

我試着這樣做,但我得到重複的數據,並沒有附加任何ItemPic數據:

$this->paginate = array(
      'conditions' => $conditions, 
      'joins' => array(
        array(
          'table' => 'item_pics', 
          'alias' => 'ItemPic', 
          'type' => 'LEFT', 
          'conditions' => array(
            'ItemPic.item_id = Item.id' 
          ), 
          'order' => 'rank ASC', 
          'limit' => 1 
        ) 

      ) 
    ); 
    $paginated = $this->Paginator->paginate(); 

回答

0

能否請您試試這個:

$this->paginate = array(
     'conditions' => $conditions, 
     'joins' => array(
       array(
         'table' => 'item_pics', 
         'alias' => 'ItemPic', 
         'type' => 'LEFT', 
         'conditions' => array(
           'ItemPic.item_id = Item.id' 
         ), 
         'order' => 'rank ASC', 
         'limit' => 1 
       ) 

     ), 
    'fields' => array('Item.*','Project.*','ItemPic.*') 
    ); 

在的Fileds部分你可能或根據您的需求可能不分配「項目」,「項目」。

謝謝

+0

這看起來似乎適用於添加'ItemPic'的東西,我可以刪除'項目'好的東西。但是,我現在正在獲取重複數據。我得到第1項與每個圖片相關聯的不同行,而不是僅具有最低等級限制1圖片的項目1。 – smerny

+0

這是它與上述使用查詢:http://pastebin.com/1VWXXGTy(我也注意到它仍然加入'Project'這裏是(下調)結果數組:HTTP://引擎收錄。 COM/nQkMUiCG – smerny

+0

我承擔'order'和'了'joins'陣列中limit'字段不工作(或至少不是這樣我預期)。 – smerny