问题
So I'm trying to work this out last night, and after thinking myself around in circles a few times decided I need some help. I did post a question about an ID field not being filled in but it got too long winded and confusing, and I realised the problem was probably based on the associations.
I'm working on a customer database. For larger business customers the relationships get a little complicated. I have 3 models, Customer, CustomerAddress and CustomerContact. A customer can have many addresses, and many contacts, but the contacts are also based at one address so an address has many contacts.
The end result I'm trying to achieve is to be able to search the data both ways, e.g.
Customer -> Address 1 -> Contact 1, Contact 2, Contact 3, etc....
Address 2 -> Contact ... ... ...
....
Or....
Customer -> Contact 1 -> Address
Contact 2 -> Address
....
The issue I'm having is that an Address must hasMany
contacts and a contact must hasOne
address, but these 2 relationships conflict because the other side should belongsTo
and it doesn't.
回答1:
Such coincidence. Just learnt this last week! As far as I can see, here is a basic relation layout
Customer hasMany Address Address belongsTo Customer
Address hasMany Contact Contact belongsTo Address
Now this covers the basic model of the first case you want to achieve. To search for Contact from Customer via Address.
As for the second case. Querying from the contact towards the Customer would be mighty expensive so, my suggestion is
Create a relation:
Customer hasMany Address and build a Model on top of this. This kind of relation is called hasMany through where two Models have a hasMany relation but have more information riding on top of the relation. For example:
Group hasAndBelongsToMany User User hasAndBelongsToMany Group
This requires a new table groups_users. Also, each group can have multiple admin. Assuming we are following all 2.x conventions. Cake doesn't allow extra columns in this table. So if this relation group_users is treated as a Model. We can add as much extra columns in it as we want.
Relation becomes GroupUser belongsTo array('User', 'Group'); User hasmany GroupUser Group hasmany GroupUser
In your case create the relation: Customer hasMany Address to a Model. Lets call is CustomerAddress.
Then CustomerAddress hasMany Contact and Contact belongsTo CustomerAddress.
hope this helps!
来源:https://stackoverflow.com/questions/27580876/how-to-correctly-set-multiple-associations-between-3-models-cakephp