2016-07-12 203 views
1

我对CakePHP 2.x文档感到困惑Model Association所以需要一点帮助,在这里连接并查找包含结果。 enter image description hereCakePHP多模型关联

Deal Table > id | title 
DealAttribute Table (has options) > id | title 
DealAttributeOption Table (belongs to DealAttribute) > id | title | deal_attribute_id 
DealsDealAttributes Table > id | deal_id | deal_attribute_id | option_id 

需要像导致

Deal [ 
    id, title 
    DealsDealAttributes [ 
     id, deal_id, deal_attribute_id, option_id 
     DealAttribute [ 
      title 
     ] 
     DealAttributeOption [ 
      title 
     ] 
    ] 
] 

我在所有三个Deal, DealAttribute, DealAttributeOptionDealsDealAttributes试图与$belongsTo,并与$hasAndBelongsToMany但没有得到包含。 现在我想如果我找到任何交易,那么所有相关的模型将进入包含。我如何设置模型关联?

+0

有你定义两个$的hasMany和$属于关联关系各自的型号?或者你是否因此而困惑?如果你遵循cakephp约定制作表格,那么你可以添加与蛋糕烘烤的模型关系。 –

+0

这将有助于查看你现有的关联代码,以查看你迄今尝试过的内容。基本上,包含外键的表的模型具有“belongsTo”关系,而与另一个包含外键的表关联的模型将是“hasOne”或“hasMany”关系。 – drmonkeyninja

+0

@drmonkeyninja我尝试了很多方法,但没有人工作,因此我很困惑,你能告诉我正确的方向吗? – Anupal

回答

0

它看起来像你的模型协会应设立这样的: -

class Deal extends AppModel { 

    public $belongsTo = [ 
     'User' 
    ]; 

    public $hasMany = [ 
     'DealsDealAttribute' 
    ]; 

} 

class DealsDealAttribute extends AppModel { 

    public $belongsTo = [ 
     'Deal', 
     'DealAttribute', 
     'DealAttributeOption' => [ 
      // Foreign key breaks naming convention so needs setting manually 
      'foreignKey' => 'option_id' 
     ] 
    ]; 

} 

class DealAttribute extends AppModel { 

    public $belongsTo = [ 
     'User' 
    ]; 

    public $hasMany = [ 
     'DealsDealAttribute' 
    ]; 

} 

class DealAttributeOption extends AppModel { 

    public $hasMany = [ 
     'DealsDealAttribute' 
    ]; 

} 

您将需要设置在DealsDealAttribute模式DealAttributeOption关联的外键,你已经从CakePHP的命名破大会(理想情况下应该是deal_attribute_option_id)。

更新

然后检索与相关记录的交易,你可以使用contain检索相关模型是这样的: -

$result = $this->Deal->find('first', [ 
    'contain' => [ 
     'DealsDealAttribute' => [ 
      'DealAttribute', 
      'DealAttributeOption' 
     ] 
    ], 
    'conditions' => [ 
     'Deal.id' => $id 
    ] 
]); 
+0

我做了同样的事情,但是当我发现交易时,只有'DealsDealAttribute'没有与其关联。 – Anupal

+0

你在做什么来检索数据。这听起来像你发现的查询是错误的! – drmonkeyninja

+0

'$ result = $ this-> Deal-> findById($ id);'这就是我在控制器中找到交易的方式。 – Anupal