问题
I want to add this CHECK in one of my tables. I am using Sequelize in a node.js api running on Postgres DB.
CHECK (
    (
        CASE WHEN UserID         IS NULL THEN 0 ELSE 1 END
        + CASE WHEN TableID      IS NULL THEN 0 ELSE 1 END
        + CASE WHEN FoodID       IS NULL THEN 0 ELSE 1 END
        + CASE WHEN RestaurantID IS NULL THEN 0 ELSE 1 END
        + CASE WHEN CategoryID   IS NULL THEN 0 ELSE 1 END
        + CASE WHEN ShipID       IS NULL THEN 0 ELSE 1 END
    )
    = 1
)
So, I need the database to enforce the check on the table where one of those columns must be not null, and only one, the others must be null.
Is there a way to do that in Sequelize?
I tried doing this:
let sql = `ALTER TABLE TestTable
ADD CONSTRAINT check_test CHECK testBool=false;`
await sequelize.query(sql, { type: sequelize.QueryTypes.RAW });
I just created TestTable with a testBool column just to test things out to see if they would run at all.
When that runs I get this ERROR:
relation "testtable" does not exist
I don't understand why the name is all lowercase. In the model definition I even have the:
freezeTableName: true
I can see the Table in the DB, I can save rows to it etc... so, it's there.
回答1:
From the feedback I got in the comments:
- use the sequelize.QueryTypes.RAW 
- follow proper naming conventions Postgres naming rules 
- run this query worked: - let sql = - ALTER TABLE test_table ADD CONSTRAINT check_test CHECK testBool=false;- await sequelize.query(sql, { type: sequelize.QueryTypes.RAW }); 
来源:https://stackoverflow.com/questions/61214694/add-sql-table-check-using-sequelize