我对CakePHP 2.x doc Model Association感到困惑。所以需要一点帮助来连接并在结果中找到包含。
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
]
]
]
我在所有三个$belongsTo
的{{1}}中使用$hasAndBelongsToMany
和DealsDealAttributes
进行了尝试,但没有获得包含。
现在我想要,如果我找到任何交易,那么所有相关的模型将包含。如何设置模型关联?
答案 0 :(得分: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'
];
}
您需要为DealAttributeOption
模型中的DealsDealAttribute
关联设置外键,因为您已经从CakePHP的命名约定中删除了(理想情况下应该是deal_attribute_option_id
)。
<强>更新强>
然后,要检索与相关记录的交易,您可以使用contain
检索相应的模型,如下所示: -
$result = $this->Deal->find('first', [
'contain' => [
'DealsDealAttribute' => [
'DealAttribute',
'DealAttributeOption'
]
],
'conditions' => [
'Deal.id' => $id
]
]);