Search code examples
node.jsmodelloopbackjs

How to add a column to an existing table in Loopback


I have 2 models, Items and Policies. Both have already been deployed, with tables created in the DB (SQL).

I want to add a relationship between them: Item -> hasOne -> policy

I added this to Item.json:

"relations": {
    "policy": {
      "type": "hasOne",
      "model": "Policy",
      "foreignKey": "policyId"
    }

And this to Policy.json

"relations": {
    "item": {
      "type": "belongsTo",
      "model": "Item",
      "foreignKey": "policyId"
    }
}

I thought that just by running the existing code, autoregenerate would notice the exiting differences, and add an extra column to the table. Instead, I get the error:

(node:216) UnhandledPromiseRejectionWarning: RequestError: Invalid column name 'policyId'.
    at handleError (C:\Users\user\Project\MyProject\node_modules\loopback-connector-mssql\node_modules\mssql\lib\tedious.js:519:15)

Which I take to mean I've missed something. No extra column was created in the Item table, of course.

What do I need to do to initiate the column being added, or do I need to do this manually?


Solution

  • If you create a relation of policy in item then you should include relation on the item Model.

    Example :

    We have two model UserFollower and User If we need to create EndUser relation in UserFollower then we changeto UserFollower with

    "properties": {
            "followee": {
                "type": "string",
                "required": true
            },
            "follower": {
                "type": "string",
                "required": true
            }
        },
      "relations": {
            "enduser_followee": {
                "type": "belongsTo",
                "model": "EndUser",
                "foreignKey": "followee"
            }
        }
    

    As per your requirement just remove below code from Policy.json

    "relations": {
        "item": {
          "type": "belongsTo",
          "model": "Item",
          "foreignKey": "policyId"
        }
    }