2014-05-18 56 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(); 
    }