Setting relationship field with multiple relationTo collections via beforeChange hook. #5453
Replies: 1 comment
-
I found the answer here: https://payloadcms.com/docs/fields/relationship#has-one-polymorphic My beforeChange hook now looks like: const AddCreatedBy: CollectionBeforeChangeHook = async ({
data,
req,
operation,
}) => {
if (operation === "create" && req.user) {
const relationTo =
req.user._strategy === "local-jwt" ? "users" : "api-keys";
data.createdBy = { relationTo: relationTo, value: req.user.id };
}
return data;
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have a readOnly relationship field "createdBy" that looks like the following:
My beforeChange hook to add the createdBy field looks like:
If I remove the readOnly and the beforeChange hook then add createdBy manually the data looks like:
instead of {createdBy: user} when I have relationTo: "users" instead of relationTo: ["users", "api-keys"]
My hook as is works for when I have relationTo: "users" instead of relationTo: ["users", "api-keys"]
but with relationTo: ["users", "api-keys"] I get a validation error. If a change the hook to update createdBy.value instead of createdBy I get an undefined error for createdBy.value.
Does anyone knopw what I am doing wrong, it would be ideal to have the createdBy field relate to either the users or api-keys collection and according to the relationship field docs I should be able to: relationship docs
Beta Was this translation helpful? Give feedback.
All reactions