Lucid insert - best way to populate two foreign keys in same model

#1

If I have a model, lets call it Comments which has two foreign keys

  • post_id
  • user_id

I can save the user relationship with

await user.comments().save(comment)

However to save the post relationship, I can only think that I would have to first set the post_id field manually then save the record

comment.post_id = post_id
await user.comments().save(comment)

Is this the way I should do it, or am I missing something?

1 Like

#2

From your description, I conclude you have a hasMany relationship from User to Comment and from Post to Comment. In that case, I think this should work:

await user.comments().save(comment)
await post.comments().save(comment)
0 Likes

#3

The problem would be that the first

await user.comments().save(comment)

Would fail (I think) because post_id is set as notNullable.

I don’t think there is any issue with me manually assigning post_id a value as I showed in my post, i was just wondering if there was a “better” way that I should be doing it.

0 Likes

#4

I do not know if there is a better way.
On the other hand, a foreign key can be nullable (but that is not always what we wish, and I personally consider that as a bad database design)
Anyway if your approach works for the moment, then just use it and hopefully @virk or someone else could drop a line here and share his/her experience with the community.

1 Like