在Yii中创建三个以上表的关系


Create a relation of more than three tables in Yii

当我尝试在Yii中创建超过三个表的关系时,我有以下方法引起了我的麻烦:

public function relations()
{
     return array(
                 'info'=>array(self::BELONGS_TO, 'Software', 'ITEM_ID'),
                 'categories'=>array(self::MANY_MANY, 'ItemCategory',
                 'item_cat_relation(item_id, cat_id)',
                 'condition'=>'categories.cat_of_type=item_meta1.item_type_id'),
                 );
}

这段代码给出了item_meta1.item_type_id

的错误

一般来说,Yii不是为处理"三表关系"而构建的。话虽如此,您应该仍然能够在关系查询中添加条件(),我认为问题只是您没有JOIN item_meta1表。有两种方法:

1)添加JOIN子句到你的关系:
return array(
  'categories'=>array(self::MANY_MANY, 'ItemCategory',
    'item_cat_relation(item_id, cat_id)',
    'join'=>'JOIN item_meta1 ON categories.cat_of_type=item_meta1.item_type_id'
  ),
);

1)在你的关系中添加一个WITH子句(假设你已经建立了另一个表的关系):

return array(
  'itemMeta'=>array(self::HAS_MANY, 'ItemMeta','item_type_id'), // I probably don't have this quite right, but you should get the idea
  'categories'=>array(self::MANY_MANY, 'ItemCategory',
    'item_cat_relation(item_id, cat_id)',
    'with'=>'itemMeta',
    'condition'=>'categories.cat_of_type=itemMeta.item_type_id')
  ),
);

我没有测试任何代码,但我已经做了类似的事情,所以它应该工作,原则上。祝你好运!