cakephp / docs

CakePHP CookBook
http://book.cakephp.org
Other
679 stars 2.58k forks source link

Junction table for belongsToMany having id column? #7936

Closed mehov closed 1 month ago

mehov commented 1 month ago

https://book.cakephp.org/5/en/orm/associations.html#belongstomany-associations

Three database tables are required for a BelongsToMany association. In the example above we would need tables for articles, tags and articles_tags. The articles_tags table contains the data that links tags and articles together. The joining table is named after the two tables involved, separated with an underscore by convention. In its simplest form, this table consists of article_id and tag_id.

I have a joining table table like that (with just article_id and tag_id), serving a belongsToMany association. When I save my data as per https://book.cakephp.org/5/en/orm/saving-data.html#saving-belongstomany-associations, I am getting:

Cannot insert row in articles_tags table, it has no primary key. Cake\Database\Exception\DatabaseException

I tried adding an index of type PRIMARY that includes both columns and it worked.

Please make it say that either an ID is required, or you have to add a multiple-column PRIMARY index on both columns.

dereuromark commented 1 month ago

Side note: Personally I always use AIID id as primary key here, on top. The data overhead is minimal, and it makes everything much easier, incl manual edit/delete if necessary through backend or otherwise. They don't have to be exposed at all.

ADmad commented 1 month ago

Please use one of the support channels for your queries.

mehov commented 1 month ago

@dereuromark Thanks for the tip, I tried that too and it worked.

@ADmad Okay, I re-read my initial OP, and it did look like a stackoverflow question, so you have a point. I edited it.

I'll make a PR