不要怂,就是干,撸起袖子干!

Commit 39a6a065 by Jan Aagaard Meier

[ci skip] Change poly assoc docs a bit. Closes #3734

1 parent 844ca10e
Showing with 8 additions and 4 deletions
...@@ -211,39 +211,43 @@ this.Comment = this.sequelize.define('comment', { ...@@ -211,39 +211,43 @@ this.Comment = this.sequelize.define('comment', {
this.Post.hasMany(this.Comment, { this.Post.hasMany(this.Comment, {
foreignKey: 'commentable_id', foreignKey: 'commentable_id',
constraints: false,
scope: { scope: {
commentable: 'post' commentable: 'post'
} }
}); });
this.Comment.belongsTo(this.Post, { this.Comment.belongsTo(this.Post, {
foreignKey: 'commentable_id', foreignKey: 'commentable_id',
constraints: false,
as: 'post' as: 'post'
}); });
this.Image.hasMany(this.Comment, { this.Image.hasMany(this.Comment, {
foreignKey: 'commentable_id', foreignKey: 'commentable_id',
constraints: false,
scope: { scope: {
commentable: 'image' commentable: 'image'
} }
}); });
this.Comment.belongsTo(this.Image, { this.Comment.belongsTo(this.Image, {
foreignKey: 'commentable_id', foreignKey: 'commentable_id',
constraints: false,
as: 'image' as: 'image'
}); });
``` ```
Note that the Image -> Comment and Post -> Comment relations define a scope, `commentable: 'image'` and `commentable: 'post'` respectively. This scope is automatically applied when using the association functions: `constraints: false,` disables references constraints - since the `commentable_id` column references several tables, we cannot add a `REFERENCES` constraint to it. Note that the Image -> Comment and Post -> Comment relations define a scope, `commentable: 'image'` and `commentable: 'post'` respectively. This scope is automatically applied when using the association functions:
```js ```js
Image.getComments() image.getComments()
SELECT * FROM comments WHERE commentable_id = 42 AND commentable = 'image'; SELECT * FROM comments WHERE commentable_id = 42 AND commentable = 'image';
Image.createComment({ image.createComment({
title: 'Awesome!' title: 'Awesome!'
}) })
INSERT INTO comments (title, commentable_id, commentable) VALUES ('Awesome!', 'image', 42); INSERT INTO comments (title, commentable_id, commentable) VALUES ('Awesome!', 'image', 42);
Image.addComment(comment); image.addComment(comment);
UPDATE comments SET commentable_id = 42, commentable = 'image' UPDATE comments SET commentable_id = 42, commentable = 'image'
``` ```
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!