CakePHP multiple HABTM relationships
I have an assets table which contains all the fields shared by all asset types, e.g. name
, path
, filetype
, size
, etc.
Now, I have 2 asset types: assets belonging to architects
and assets belonging to construtors
. So I set up HABTM relationships on these 2 types, i.e.
|-------- architects_assets ------- architects
assets|
|-------- constructors_assets ----- constructors
The problem is, when creating an asset, I want each asset to be one of either an architects_asset
or a constructors_asset
-- assets are never both an architect and constructor asset.
The simple solution would be to create architect_assets
and constructors_assets
tables and drop the assets
table, since this way you could add, edit, view, delete each type separately. Alternatively, I'm thinking I could create architects_asset_a开发者_开发技巧dd
and constructors_asset_add
actions in the assets
controller, but then I'd have to do the same for the edit, view and delete, which seems bloated.
How would you approach this problem?
I have been able to solve this problem using hasMany through relationships. This meant creating separate controllers for architects_assets
and construtors_assets
, but this suits me given I needed to make clear distinction between the 2 asset types.
The resultant models:
//asset
class Asset extends AppModel {
public $hasMany = array('ArchitectAsset', 'ConstructorAsset')
}
//architect asset
class ArchitectAsset extends AppModel {
public $belongsTo = array('Architect, Asset');
}
//architect
class Architect extends AppModel {
public $hasMany = 'ArchitectAsset';
}
//and the same for the ConstructorAsset and Constructor models
I think modifying the assets Model to add new CRUD methods to support these two actions would be a good idea.
Sure it would make you're Model code larger, but it would allow you to keep all the assets on the same table, in case you need to do some operations on them that are not related to the architecture or constructor relationship.
精彩评论