# Many to Many where one table can be any table?

**URL:** <https://discourse.cakephp.org/t/many-to-many-where-one-table-can-be-any-table/8992>\
**Category:** Need Help\
**Created:** [February 10, 2021, 1:45am UTC](https://discourse.cakephp.org/t/many-to-many-where-one-table-can-be-any-table/8992 "2021-02-10T01:45:21Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![calzone](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/calzone/32/305_2.png) [@calzone](https://discourse.cakephp.org/u/calzone)\
**Post date:** [February 10, 2021, 6:16am UTC](https://discourse.cakephp.org/t/many-to-many-where-one-table-can-be-any-table/8992/2 "2021-02-10T06:16:18Z")

</div>

Well… after many iterations of DDG → Google searches… lo and behold, I came across this:

> [@Multiple belongsToMany](https://discourse.cakephp.org/t/multiple-belongstomany/5698):
>
> Is there a (simple) way to have multiple belongsToMany associations ? The goal is to tag everything. So, I have a Tags table and would like it to be associated with Articles, Categories, Images etc. There used to be a tagEverything (I don’t remember the name exactly) plugin but it was cake 2 only.

I guess my search on here was insufficient.

I tried seeing what it might take to do this as a behavior, but that didn’t seem any clearer. Then, the suggestion to denormalize my tags into a single column in every table was a total non-starter.

So I took @Zuluru’s suggestion in that thread … closed my eyes and just tried and hoped.

Instead of setting it up as a `belongsToMany()`, I created a `belongsTo()` for each each table using the entity\_tags table in the `EntityTagsTable.php` model… I set up corresponding `hasMany()` relationships in my other tables back to `EntityTags`.

In each `belongsTo()`, I added `'setFinder' => ['tabl_name' => 'xxxxxxxxx']` (where xxxxxx is just whichever one of several tables I’m associating to `EntityTags`. (Because `tabl_name` is the name of the column in my bridge table that tells me which entity the `f_key` field is for).

Fingers crossed, I tweaked the view controller for one of those tables and threw in

`'contain' => ['EntityTags','EntityTags.Tags'],`

to my `->get()`

And… I’m encouraged to report that that much of this whole adventure is indeed working!

Now I need to see how it works with actual tag assignment and saving (need to test the CUD in CRUD, although tags aren’t about U really… they’re C and D as far as write ops)

As well, I’m going to see if I can go full monty and use `belongsToMany()` in `Tags` instead of `belongsTo()` in `EntityTags`… if for no other reason than it will save me a level in the returned query results (i.e., “bypassing” `EntityTags` and just giving me actual tags per each record… as it is now, I have` $xxxxxxx->entity_tags[n]->tags[y]` )

---

_[View the full topic](https://discourse.cakephp.org/t/many-to-many-where-one-table-can-be-any-table/8992)._
