I have 2 models that need to be linked by a habtm relationship, having this table-structure:
CATEGORIES:
id | name | ..
-----------------------
1 | test | ..
POSTS:
id | name | other_id | ..
---------------------------------
1 | test | 5 | ..
CATEGORIES_POSTS:
id | category_id | other_id
--------------------------------
1 | 1 | 5
I need to get the posts from the category side, but don’t seem to be able to set the habtm relation correctly. The important thing, that I didn’t mention so far, is that the id used in the Post-model is not id but other_id. This is what I tried so far (all in the Category-model):
-
set the associationForeignKey to ‘other_id’
in the sql-query it has:
CategoriesPost.other_id = Post.idfragment -> wrong relation (should beCategoriesPost.other_id = Post.other_id -
set the associationForeignKey to false and add a condition
CategoriesPost.other_id = Post.other_idnow the sql fragment is
CategoriesPost. = Post.id–> sql error -
set the associationForeignKey to
CategoriesPost.other_id = Post.other_idwell .. this is an error as well, as Cake takes the input as 1 field:
CategoriesPost.other_id = Post.other_id = Post.id
I know I could achieve to relation through 2 hasMany links, but that gives me a lot of queries instead of 1
Thanks in advance!
just change the post model primaryKey on the fly for some operations you need to….
To do so, just need to do $this->primaryKey = ‘other_id’ OR in a controller $this->Post->primaryKey= ‘other_id’
that would do the trick.
But remember, if you are retrieving data from all associations and you have more associations than this one then the other associations if they use Post.id are going to fail since primary key is Post.other_id
you should do a find function in your post models for when you are using this union, something like this:
if you need to join it with other models gets a little more tricky i will recommend to use joins for that (try looking at the linkable bhaviour code to see how)
I strongly suggest to use only ONE primary key since it’s not really helpfull a second one. A primary key should be unique anyway and you can associate anything with just one.