2014-05-18 101 views
0

我有表CakePHP的:連接操作不工作

Items, Attributes,Taxonomies, Taxonomy_attributes,Item_attributes. 

Taxonomy_attributes有兩個字段attribute_id(這是一個外鍵的屬性表的ID)和taxonomy_id(這是一個外鍵分類表的ID) 。 另一方面,Item_attributes有兩個字段attribute_id(它是ID屬性表的外鍵)和item_id(它是ID項表的外鍵)。 屬性表具有以下字段: - 名稱,類型和可檢查(可以是0或1)。 項目表具有字段ID和模型。 分類標準表具有字段if和name。

我想向屬性模型添加一個方法,該方法返回所有可檢查等於1的屬性的列表,並加入項目和分類,返回項目模型&分類名稱爲每個屬性。

我的代碼如下: -

public function getCheckables($checkable) 
{ 
    $data = $this->find('all',array(
       'fields' => array('Attribute.name', 'Attribute.type', 'Item.model', 'Taxonomy.name'), 
       'conditions' => array('Attribute.checkable' => 1), 
       'joins' => array(
          array(
           'table' => 'item_attributes', 
           'alias' => 'ItemAttribute', 
           'type' => 'INNER', 
           'conditions' => 'ItemAttribute.Item_id = Item.id', 
          ), 
          array( 
           'table' => 'items', 
           'alias' => 'Item', 
           'type' => 'INNER', 
           'conditions' => 'ItemAttribute.item_id = Item.id' 
          ), 
          array( 
           'table' => 'taxonomy_attributes', 
           'alias' => 'TaxonomyAttribute', 
           'type' => 'INNER', 
           'conditions' => 'TaxonomyAttribute.Taxonomy_id = Taxonomy.id' 
          ) 

        ), 
        'recursive'=>-1 
       ) 
       ); 
       pr($data); die(); 
} 

可有人指導我用正確的代碼?

+0

你有沒有在你的模型中定義與其他3任何樣的關係? – Tanatos

回答

1

您的兩個連接有相同的條件:'conditions'=>'ItemAttribute.Item_id = Item.id',如果是第一個,Item表還沒有加入,如果是第二個,因爲你的第一個條件是錯誤的,ItemAttribute表沒有被加入。

+0

你說得對。兩個連接都具有相同的條件。但也有其他一些問題。我接受你的答案,因爲你的答案是正確的。 @Tanatos –

0

實際的解決方案

public function getCheckables($checkable) 
    { 
     $data = $this->find('all',array(
        'fields' => array('Attribute.name', 'Attribute.type', 'Item.model', 'Taxonomy.name'), 
        'conditions' => array('Attribute.checkable' => 1), 
        'joins' => array(

           array(
            'table' => 'item_attributes', 
            'alias' => 'ItemAttribute', 
            'type' => 'INNER', 
            'conditions' => 'ItemAttribute.attribute_id = Attribute.id', 
           ), 
           array( 
            'table' => 'items', 
            'alias' => 'Item', 
            'type' => 'INNER', 
            'conditions' => 'ItemAttribute.item_id = Item.id' 
           ), 
            array( 
            'table' => 'taxonomies', 
            'alias' => 'Taxonomy', 
            'type' => 'LEFT', 
            'conditions' => 'Item.category_id = Item.id' 
           ) 



         ), 
         'recursive'=>-1 
        ) 
        ); 
        pr($data); die(); 
    }