Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nwalberts/1b92459a9af6d163dc95660b22462058 to your computer and use it in GitHub Desktop.
Save nwalberts/1b92459a9af6d163dc95660b22462058 to your computer and use it in GitHub Desktop.

Some Notes and Reflections on Week 6 Database Associations

Naming Conventions

  • migration table name: plural
  • model / class name: singular
  • tableName(): refers to table name, so plural
  • relation names: plural if "HasManyRelation", singular if "BelongsToOne"
  • join: refer to the tableName of the model you are on, and determine what column helps connect the two tables (usually either id or somethingId)
  • usually, you start with the tableName of the model you are on, then if its a hasMany, you will be doing somethings.id to otherThings.somethingId
   static get relationMappings() {
        const { Pet } = require("./index.js")
        return {
            pets: {
                relation: Model.HasManyRelation,
                modelClass: Pet,
                join: {
                    from: "species.id",
                    to: "pets.speciesId"
                }
            }
        }
    }
ALL OF THIS CRAZY relationMapping SHIT IS JUST SO THAT WE CAN CALL $relatedQuery() like....once or twice in the whole ding dang app. This is cray, bae
const fido = await Pet.query().findOne({ name: "Fido"})
fido.$relatedQuery("species") // dog {}
const dog = await Pet.query().findOne({ name: "Dog"})
dog.$relatedQuery("pets") // [ pet {} ]

Note: other places where naming gets funky

  • when passing data from the backend to the front e.g.
const arrayOfUnicorns = await Unicorn.query()
res.status(200).json({ unicorns: arrayOfUnicorns})

means we have to call on the same unicorns key in parsing the fetch request in react

const response = await fetch("api/v1/unicorns")
const unicornData = await response.json()
setUnicorns(unicornData.unicorns) 

We have to do the same for sending data from the frontend to the backend

const response =  await fetch("/api/v1/unicorns", {
  method: "POST",
  body: JSON.stringify({ newUnicorn: unicornFormData })
  ...
})
unicornsRouter.post("/", async (req, res) => {
     const unicornObject = req.body.newUnicorn
}

Todo to practice

  • make a bunch of species and pets and play around with different combinations. understand how foriegn key id helo connect tables
  • change the "keys" of data that is being sent in res.json() or in the body of a fetch POST
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment