I am confused with the CakePHP 2.x doc Model Association So need a little help over here to connect and find contains in result.
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
Need result like
Deal [
id, title
DealsDealAttributes [
id, deal_id, deal_attribute_id, option_id
DealAttribute [
title
]
DealAttributeOption [
title
]
]
]
I tried with $belongsTo
and also with $hasAndBelongsToMany
in DealsDealAttributes
of all three Deal, DealAttribute, DealAttributeOption
but didn't get the contains. Now i want if i find any Deal then all the associated models will comes in contains. How do i set up the Models association?
It looks like your model associations should be set up something like this:-
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'
];
}
You will need to set the foreign key for the DealAttributeOption
association in the DealsDealAttribute
model as you've broken from CakePHP's naming convention (it should ideally be deal_attribute_option_id
).
Update
Then to retrieve a deal with the associated records you can use contain
to retrieve the relevant models like this:-
$result = $this->Deal->find('first', [
'contain' => [
'DealsDealAttribute' => [
'DealAttribute',
'DealAttributeOption'
]
],
'conditions' => [
'Deal.id' => $id
]
]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.