检查项目是否没有错误链接 - 这就是“外键约束”的目的是为了?
我现在在 SQLAzure 工作。
我正在设置一个设计,其中每个用户都有多个地址,
当用户下订单时,我想将该订单链接到用户和几个地址。
所以我的桌子看起来像:
用户
- 身份证
- 姓名
- 等等
地址
- 身份证
- 用户 ID(外键)
- 街道
- 等等
订单
- 身份证
- 用户 ID(外键)
- DeliveryAddressId(外键)
- BillingAddressId(外键)
- 等等
有没有办法在 SQL Server 中设置检查,以便用户可以在任何情况下(例如,通过破解 HTML POST)都不要提交带有与所提交的 UserId 不链接的 AddressId 的订单。我已经查看了文档中的“外键约束”,但这似乎并不是我想要的。
任何有关尝试什么或阅读什么教程的建议将不胜感激。
I'm working in SQLAzure at the moment.
I'm setting up a design where each User has a number of Address's
When the user then places an Order, then I want to link that Order to both the User and to a couple of Addresses.
So my tables look like:
User
- Id
- Name
- etc
Address
- Id
- UserId (Foreign Key)
- Street
- etc
Order
- Id
- UserId (Foreign Key)
- DeliveryAddressId (Foreign Key)
- BillingAddressId (Foreign Key)
- etc
Is there a way I can I set up a check within SQL Server so that a user can't under any circumstances (e.g. by hacking an HTML POST) submit an Order with an AddressId which is not linked to the same as the submitted UserId. I've looked at "foreign key constraints" in the docs, but this doesn't seem to be quite what I'm looking for.
Any suggestions of what to try - or what tutorials to read - would be most appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除了 Address 表中的主键(在 Id 上)之外,您还应该在 (Id,UserId) 上声明另一个键约束,即 UNIQUE 约束。
然后,您可以将现有的 FK 从订单替换为地址,或者添加其他 FK,以检查两列
正如我所说,如果您愿意,您可以将这些全部添加为附加约束。
因此,通过一些轻微的命名调整,您的表格将呈现如下:
并尝试使用一些应该有效的插入,除了最后一个(用户/地址不匹配)之外,它有效:
结果:
In addition to your primary key in the Address table (on Id), you should also declare another key constraint, a UNIQUE constraint, on (Id,UserId).
You can then either replace your existing FKs from Order to address, or add additional ones, that check both columns
As I say, you can add these all as additional constraints, if you want to.
So, with some slight naming tweaks, your tables are rendered as this:
And trying it our with some inserts that should work, except for the last (where there's a user/address mismatch), it works:
Results:
创建一个 ON INSERT 触发器来执行您想要强制执行的任何其他逻辑。
缺点是用户在尝试使用错误地址时会收到错误消息...为了主动,您也应该在 GUI 中执行此检查。
create an ON INSERT trigger to do any additional logic that you want to enforce.
the downside will be the user will get an error message when they try with a bad address... to be proactive, you should do this check also in the GUI.
使用从 Order (UserID, DeliveryAddressID) 到 Address (UserID, ID) 的复合外键可以吗? (与 BillingAddressID 类似)
Would having a composite foreign key from Order (UserID, DeliveryAddressID) to Address (UserID, ID) do it? (Similarly for BillingAddressID)