Jerome
Jerome

Reputation: 2761

Storing additional values on a many-to-many relationship in KeystoneJS

I have a many-to-many relationship between my Post and Tag lists and I want to record the date when a tag is added to a post. I can't see how to add this field when defining a many-to-many relationship between these lists.

Does it mean that I have to manually create a PostTag list that has a one-to-many relationship with the Post list and another one-to-many relationship with the Tag list?

Upvotes: 1

Views: 364

Answers (1)

Molomby
Molomby

Reputation: 6559

There's currently no mechanism for adding fields to the relationship itself (although it has come up before). The thinking being that, if you need to store additional information "on" the relationship, it stops being a pure relationship and becomes a list, with fields, like any other.

Does it mean that I have to manually create a list POSTTAGS that has a O2M relationship with POST and another O2M relationship with TAGS?

Yes, this is one way of solving the problem and probably the best in most instances. The downside is that it changes the interface you'll be given for adding tags to posts; you'll now need to "create" the PostTag items which might be clunkier from a UX perspective.

Another potential solution would be to leave the many-to-many relation field as is and store the extra data somewhere else. For example you could add a json field to posts called taggedDates and use hooks to record when links are created or destroyed. Note, to make this work, you may need a hook on both the Post and Tag lists, as (depending on how the fields are configured) the relationship between items could be modified from either side.

The former solution is probably better most of the time but the latter does let you keep the nice many-to-many interfaces in the Admin UI, if that's what you're prioritising.


Bonus future solution – This doesn't help you right now but there's been talk of adding an escape hatch that lets developers selectively override parts of the generated Prisma schema. It's not general solution for "fields on relationship" problem but if really all you needed was a timestamp for when the link was created, this functionality would let you do that. Unfortunately you'd need to use context.prisma directly to query the values and, of course, the feature doesn't actually exist yet (but there's a good chance it will land in the next month or two).

Upvotes: 1

Related Questions