Search code examples
backand

How to make foreign key required?


For the model example given in the documentation, I noticed that you can create a pet object without requiring a owner. How do I specify in the JSON that owner is required?

I see the Required switch from the Fields tab, but the switch doesn't move when I click on it.

[
  {
    "name": "pets",
    "fields": {
      "name": {
        "type": "string"
      },
      "owner": {
        "object": "users"
      }
    }
  },
  {
    "name": "users",
    "fields": {
      "email": {
        "type": "string"
      },
      "firstName": {
        "type": "string"
      }
      "pets": {
        "collection": "pets",
        "via": "owner"
      }
    }
  }
]

Solution

  • Currently in the JSON the required field is not supported for foreign-key but you can workaround it. I'm from Backand and we actually plan to add it in soon, but meanwhile you can do either:

    1. Add server side Action in the Before Create and Before Update events of "pets" object and check for null value, and empty throw an error. Use the following code:

        try{
            if (userInput.items == null){
                throw new Error('must have owner');
            }
        }
        catch(err){
            throw new Error('must have owner');
        }

    1. Other option is to access the MySQL database directly and set the column to be NOT NULL. After you done open the pets object page and click "Sync with Database". It won't show any indication in Backand but will do the work.