Harry
Harry

Reputation: 863

CakePHP - Custom hasOne Object Association - Using a Join Table instead of in-table foreign keys?

In CakePHP, I'm trying to build a $hasOne relationship, but I can't add a foreign key to the tables (for legacy reasons). Is there any way I can create a join table (object1_object2) and link them together like this? I want to leverage Cake's powerful object relationship functionality, so if there's a way I can make this custom association permanent throughout the model, without always building a custom $options array for each find(), that'd be great. (Maybe a bindModel in the Model's initalize()?)

Thanks!

Upvotes: 1

Views: 2032

Answers (2)

death_au
death_au

Reputation: 1302

If you want to use a join table, I believe you will have to use a hasAndBelongsToMany (HABTM) relationship, even though you will never have 'many'. The data will obviously behave differently to a standard hasOne relationship, but at least the relationship will exist.

There might be a way around it using the 'conditions' field of the hasOne relationship, but I suspect that you still have to specify a foreign key (or it will default to 'object2_id' anyway) and it will probably still attempt to do a join based on that foreign key.

Upvotes: 2

Related Questions