Home > Net >  Is it necessary to do entity relationship validation in the business logic layer when using MySQL?
Is it necessary to do entity relationship validation in the business logic layer when using MySQL?

Time:09-29

Let's say I have a book database server using MySQL. There are two entities

  1. Book
  2. Author With one to many relationship between them, one author can have many books.

There is a route in the backend to create new books with an author. The body of the request is the following

{
   bookTitle: "title",
   authorId: 1
}

Is it necessary for the business logic layer to first check if there is an record in the Author table with authorId = 1 before inserting the new book? Or leaving this validation to the database itself because it will throw a foreign error anyway.

Thanks for your help!

CodePudding user response:

Yes you should validate this. One way to do this in mysql automatically is to make sure you have the correct foreign keys setup.

Even with all of that correctly done, it's still a good idea for your backend/api to first grab the author from the database so you can return a more specific error if it didn't exist.

In most real-world applications, usually there's also permissions involved. Can all your users insert books for any author?

  • Related