简体   繁体   中英

LoopBack Automigrate Call Order

I am using LoopBack auto migrate to create MySQL database tables from models during app boot. My Account model define a hasAndBelongsToMany relationship with my Credit model, and visa versa.

I am trying to create a credit in account, but I get an SQL error. "Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '3 ORDER BY id LIMIT 1' at line 1"

According to my logging, it seems that the automigrate does not happen in order defined in my automigrate.js file, and that some arbitrary order is assigned by LoopBack, which causes the Account table to not be created when trying to add the credit to it...

The order that loopback creates automigrate table according to my logging, it first creates accounts, then creditaccounts, then credit... I need it to be account, credits, then creditaccounts.

My question is thus, how can I control the order in which LoopBack creates database tables when using auto migrate? Or am I missing something?

Condensed version of my server/boot/automigrate.js file:

app.automigrate('account', function(err) {
  server.models.Account.create({id:1}, function(err, record) {
    //handle errors here
  });
});

app.automigrate('credit', function(err) {
  server.models.Credit.create({id:1}, function(err, record) {
    //handle errors here
  });
});

app.automigrate('creditaccount', function(err) {
  server.models.Account.findById({id:1}, function(err, account) {
    server.models.Credit.findById({id:1}, function(err, credit) {
      account.credits.add(credit, function(err, creditaccount) {
        //error handling
      })
    });        
  });
});

The solution has nothing to do with automigrate, the SQL error was because I was trying to call Account.findById with an object as first parameter, instead of a primitive parameter for id... thus it should be:

app.automigrate('account', function(err) {
  server.models.Account.create({id:1}, function(err, record) {
  //handle errors here
  });
});

app.automigrate('credit', function(err) {
  server.models.Credit.create({id:1}, function(err, record) {
    //handle errors here
  });
});

app.automigrate('creditaccount', function(err) {
  server.models.Account.findById(1, function(err, account) {
    server.models.Credit.findById(1, function(err, credit) {
      account.credits.add(credit, function(err, creditaccount) {
        //error handling
      })
    });        
  });
});

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