Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

belongsTo vs hasMany in Sequelize.js

What's the difference between B.belongsTo(A) and 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?

like image 854
khex Avatar asked Nov 29 '13 17:11

khex


People also ask

What is the difference between hasMany and belongsTo?

belongsTo(B) association means that a One-To-One relationship exists between A and B , with the foreign key being defined in the source model ( A ). The A. hasMany(B) association means that a One-To-Many relationship exists between A and B , with the foreign key being defined in the target model ( B ).

How do you use belongsTo in Sequelize?

You can make the Task model belongs to the User model by calling the belongsTo() method from the Task model like this: Task. belongsTo(User); The belongsTo() method above will associate the Task model with the User model, adding the UserId attribute to the Task model as the foreign key constraint.


1 Answers

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.

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 association, the foreignKey should be the same.

Example:

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

which generates:

CREATE TABLE IF NOT EXISTS `Albums` (`id` INTEGER NOT NULL auto_increment, `artist_id` INTEGER, PRIMARY KEY (`id`)) ENGINE=InnoDB; 
like image 135
Jan Aagaard Meier Avatar answered Oct 09 '22 09:10

Jan Aagaard Meier