loopbackjs – Strongloop loopback:如何在引导脚本中的模型实例上添加相关的模型实例

我正在为学校平台开发API.

我想在启动脚本中迁移和播种数据库,而我还在开发中.

我可以创建学校实例,组实例和人员实例,但我无法弄清楚如何在人员实例和组实例之间添加关系(多对多)

这是我的Person .json文件:

{
  "name": "Person",
  "base": "User",
  "strict": true,
  "idInjection": true,
  "properties": {
    "name": {
      "type": "string",
      "required": true
    },
    "firstName": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "groups": {
      "type": "hasAndBelongsToMany",
      "model": "Group"
    },
    "school": {
      "type": "belongsTo",
      "model": "School"
    }
  },
  "acls": [],
  "methods": []
}

这是我的group.json文件

{
  "name": "Group",
  "base": "PersistedModel",
  "strict": true,
  "idInjection": true,
  "properties": {
    "name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "people": {
      "type": "hasAndBelongsToMany",
      "model": "Person"
    },
    "school": {
      "type": "belongsTo",
      "model": "School"
    }
  },
  "acls": [],
  "methods": []
}

这是我的启动脚本:

var async = require('async');

module.exports = function(app) {
    var mysqlDs = app.dataSources.mysqlDs;
    var boysNames = ["Lucas", "Liam", "Arthur", "Vince", "Noah", "Finn", "Mathis", "Louis", "Adam", "Jules", "Lars", "Seppe", "Stan", "Alexander", "Leon", "Kobe", "Victor", "Matteo", "Milan", "Mats", "Vic", "Wout", "Daan", "Senne", "Ferre", "Tuur", "Nathan", "Elias", "Warre", "Jack", "Felix", "Cas", "Thomas", "Lowie", "Robbe", "Lewis", "Rayan", "Nand", "Sem", "Maxim", "Emiel", "Jasper", "Oscar", "Mauro", "Sam", "Mohamed", "Luca", "Bent", "Ruben", "Simon", "Imran", "Jayden", "Lou", "Viktor", "Bas", "Lenn", "Rune", "Lukas", "Eden", "Emile"];
    var girlsNames = ["Emma", "Louise", "Elise", "Ella", "Marie", "Noor", "Lena", "Julie", "Lotte", "Olivia", "Anna", "Elena", "Mila", "Lore", "Fien", "Nina", "Lina", "Nora", "Laura", "Juliette", "Charlotte", "Lisa", "Amber", "Amélie", "Fleur", "Renée", "Lily", "Sara", "Camille", "Hanne", "Luna", "Liv", "Roos", "Helena", "Sarah", "Sofia", "Janne", "Noa", "Jade", "Nore", "Fenna", "Axelle", "Kato", "Alice", "Aya", "Jana", "Lize", "Paulien", "Amelie", "Lucie", "Lara", "Zoë", "Mona", "Manon", "Leonie", "Ines", "Oona", "Laure", "Mira", "Febe"];
    var names = ["Jong","Jansen","Vries","Visser","Jans","Bakker","Dijk","Vos","Smit","Berg","Boer","Groot","Janssen","Jacobs","Veen","Bos","Bergman","Hendriks","Dekker","Mulder","Willems","Meijer","Graaf","Leeuwen","Vermeulen","Koster","Peeters","Brouwer","Kok","Peters","Smits","Linden","Vliet","Wit","Beekman","Bosch","Meer","Koning","Beek","Haan","Vermeer","Verhoeven","Bruijn","Jonge","Heuvel","Martens","Dam","Hoek","Pieters","Walle","Bruin","Timmermans","Prins","Wouters","Janssens","Blom","Velde","Loon","Lange","Maas","Mol","Dijkstra","Post","Wal","Maes","Dieleman","Hermans","Jager","Stam","Gerrits","Groen","Roos","Wijk","Kuiper","Broek","Leeuw","Lambert","Kroon","Verdonck","Geerts","Boon","Hoekstra","Schouten","Gastel","Brink","Goossens","Steen","Bleijenberg","Bijl","Dubois","Jonker","Rooij","Driel","Pol","Ruiter","Stevens","Horst","Verbeek","Mertens","Ende","Sanders","Driessen","Huisman","Kooij","Schipper","Waal","Laan","Scholten","Vink","Ven","Postma","Aerts","Santen","Roovers","Verhulst","Verschoor","Ham","Moerman","Rijn","Bax","Franken","Eijk","Martin","Bosman","Meulen","Veenstra","Mostert","Velden","Harms","Wolters","Zanten","Claes","Poot","Ridder","Ginkel","Doorn","Heijden","Oost","Os","Blok","Kramer","Simons","Kuipers","Rovers","Cornelis","Dupont","Valk","Zwart","Gerard","Verweij"]

    //first lets recreate all databases
    mysqlDs.automigrate(function(){
        console.log("tables recreated: let's seed");

        async.parallel({
            schools: async.apply(createSchools)
            // ....
        }, function(errFase1, resultsFase1) {
            if (errFase1) throw errFase1;

            async.parallel({
                groups: async.apply(createGroups, resultsFase1.schools),
                persons: async.apply(createStudents, resultsFase1.schools),
            }, function(errFase2, resultsFase2) {
                if (errFase2) throw errFase2;

                // ???????????????????????????????????

                // ??? HOW TO add a relation between the persons and the groups
                // a person must be able to live 
                // in multiple groups

            });
        });
    });

    function createSchools(cb) {
        var School = app.models.School;
        School.create([
            {
                "name": "Harvard",
                "address": "xxx",
                "zip": "0000",
                "place": "yyy"  
            },
            {
                "name": "Oxford",
                "address": "xxx",
                "zip": "0000",
                "place": "yyy"  
            }
        ], cb);
    }



    function createGroups(schools,cb) {
        var Group = app.models.Group;
        Group.create([
            { "name": "Class 1", "schoolId": schools[0].id },
            { "name": "Class 2", "schoolId": schools[0].id },
            { "name": "Class 3", "schoolId": schools[0].id },
            { "name": "Class 4", "schoolId": schools[0].id },
            { "name": "Class 5", "schoolId": schools[0].id },
            { "name": "Class 6", "schoolId": schools[0].id },
            { "name": "Class 1", "schoolId": schools[1].id },
            { "name": "Class 2", "schoolId": schools[1].id },
            { "name": "Class 3", "schoolId": schools[1].id },
            { "name": "Class 4", "schoolId": schools[1].id },
            { "name": "Class 5", "schoolId": schools[1].id },
            { "name": "Class 6", "schoolId": schools[1].id },
        ], cb);
    }

    function createStudents(schools,cb) {
        var Person = app.models.Person;
        var students = [];
        for (var i = 0; i < 240; i++) {
            chooseFrom = (i%2 == 1) ? girlsNames : boysNames ;
            students.push({
                "name": names[i%names.length],
                "firstName": chooseFrom[i%chooseFrom.length],
                "username": "student"+i,
                "password": "testje",
                "email": "student"+i+"@mailinator.com",
                "emailVerified": true,
                "schoolId": schools[Math.floor(i/120)].id
            });
        };
        Person.create(students, cb);
    }
};

要将学生添加到组中,我希望这样的事情可以解决问题:

Group.findOne(function(err, group){
    console.log(group);
    group.people().add(students[0].id);
})

我找不到关于这个具体问题的任何教程.

我调试了bootscript,并检查了组变量,它是一个ModelConstructor.我猜我可以通过people()函数获取相关人员,但是如何将人员添加到特定组?

最佳答案 在这个上找到了正确的文档:

http://apidocs.strongloop.com/loopback-datasource-juggler/#relationmixin-hasandbelongstomany

点赞