SQL Sequelize.js 中的属于与 hasMany

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20290815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 23:18:27  来源:igfitidea点击:

belongsTo vs hasMany in Sequelize.js

sqlnode.jsormsequelize.js

提问by khex

What's the difference between B.belongsTo(A)and A.hasMany(B)

什么之间的区别B.belongsTo(A)A.hasMany(B)

Artist = sequelize.define('Artist', {});
Album = sequelize.define('Albums', {});

Album.belongsTo(Artist, foreignKey: 'album_belongsl_artist');
Artist.hasMany(Album, foreignKey: 'artist_hasmany_albums');

if it in both cases creates the depended tables in Album?

如果它在这两种情况下都创建了依赖表Album

回答by Jan Aagaard Meier

When you do Album.belongsTo(Artist)you are creating the relation enabling you to call album.getArtist(). Artist.hasMany(Album)links the association the other way, enabling you to call artist.getAlbums(). If you only did one of those two, e.g. if you only did Album.belongsTo(Artist)you would be able to retrieve the artist of an album, but not all albums of an artist.

当您这样做时,Album.belongsTo(Artist)您正在创建使您能够调用album.getArtist(). Artist.hasMany(Album)以另一种方式链接关联,使您能够调用artist.getAlbums(). 如果你只做了这两个中的一个,例如如果你只做了,Album.belongsTo(Artist)你将能够检索专辑的艺术家,但不是艺术家的所有专辑。

Notice however, that because of the foreign key given in your example, you are effectively creating two relations. The generated table looks like this:

但是请注意,由于您的示例中给出了外键,因此您有效地创建了两个关系。生成的表如下所示:

CREATE TABLE IF NOT EXISTS `Albums` (`id` INTEGER NOT NULL auto_increment , `album_belongsl_artist` INTEGER, `artist_hasmany_albums` INTEGER, PRIMARY KEY (`id`))

If you only want one assocation, the foreignKey should be the same. Example:

如果您只想要一个关联,则外键应该是相同的。例子:

Album.belongsTo(Artist, {foreignKey: 'artist_id'});
Artist.hasMany(Album,{ foreignKey: 'album_id'});

which generates:

它产生:

CREATE TABLE IF NOT EXISTS `Albums` (`id` INTEGER NOT NULL auto_increment , `album_id` INTEGER, PRIMARY KEY (`id`)) ENGINE=InnoDB;