Hi,
I would ask if there is a smart way to access payload generated ID
for collection in CollectionBeforeChangeHook
?
Because right now, imagine the situation:
Users
has relation to collection BankAccount
and in opposite way relation also exist. It is one to one always.Users{
userId: <payloadGenerated>
bankAccountId: <idFromBankCollection>
}
BankAccount{
bankAccoutnId: <payloadGenerated>
owner: <idFromUserCollection>
}
For that case, I need two hooks:
CollectionBeforeChange
on Users
to create as local API BankAccount document
and populate in Users
bankAccountId
.CollectionAfterChange
on Users
to find and update as local API BankAccount document
with userId
.That is because in CollectionBeforeChangeHook
there is no pre-generated access to ID for not created yet User document. So is there a way to do it in a smarter way? Write own generation for ID on Users, and then use just one hook? But then I need own validations for checking if id is already existing?
Maybe someone has better idea how to proceed with such cases? Or should I avoid bi-directional relations, and simple embedding them on users?
@dawidmachon you're right in that if the operation is create
, there is not yet an ID to use. Your solution looks fine to me, does it work? Just to sum it up:
bankAccountId
to the userowner
with their userId
This will work for that initial connection but updates on either end of the relationship will also need to be wired in—and this may lead to infinite loops. There are ways around this, like maintaining a hidden skipHooks
field on the collection, I've done something similar to this in our Stripe plugin. Others have run into this same need, though, and there's a community-supported plugin if you want to check it out: https://github.com/TimHal/pcms-backpop. I have not tested this myself but it might work for you 👍
great answer. Thanks a lot for your response! Great warning for infinite loops.
It's working, but I was curious if there is a 'smarter' way to do this. ;) Thanks for plugin!
Star
Discord
online
Get dedicated engineering support directly from the Payload team.