简体   繁体   中英

SailsJS: Many-to-Many association in MySQL

I've tried to search before posting this question, but no success.

I'm having some troubles trying to understand the best way to achieve a many-to-many association in SailsJS.

Ex:

Hospital has many specialties

Specialty has many hospitals

How do I represent the tables in MySQL so the SailsJS operate on them?

I have an Hospital table and a Specialty table. Do I have to have an Hospital_Specialty (not sure about if this is the correct tablename to use) table to handle those associations? Like:

Hospital_Specialty

id: int

hospital_id: int

specialty_id: int

I've read the documention but no luck on getting a proper way to achieve what I need.

Thanks in advance

Edit: My initial answer was totally wrong.

The documentation for setting up many <-> many relationships is here: Many-to-Many | Sails.js

First of all, you'll want to work in Waterline rather than mysql to get this to work properly. You can set up a many relationship in your model like so:

Specialty.js Model

module.exports = {
  attributes: {
    hospitals:{
      collection: 'hospital',
      via: 'specialties'
    }
  }
}

Hospital.js Model

module.exports = {
  attributes: {
    specialties:{
      collection: 'specialty',
      via: 'hospitals'
    }
  }
}

This will set up the required intermediate tables.

Up to you if you want to use plurals or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM