2017-10-11 49 views
0

將同一個表與多個表相關聯的最佳方式是什麼?我在MySQL數據庫中有3個表,Owners,Pets,Posts。業主有很多寵物,業主也有很多帖子。當我做的文章和寵物模型的關聯如下將一個表與「hasMany」其他表相關聯

Posts.associate = function(models) { 
    Posts.belongsTo(models.Owners, { 
     foreignKey: { 
      allowNull: false 
     } 
    }); 
}; 
Pets.associate = function(models) { 
    Pets.belongsTo(models.Owners, { 
     foreignKey: { 
      allowNull: false 
     } 
    }); 
}; 

而在業主模型我試圖讓聯想,有很多,對於這樣的:

Owners.associate = function(models) { 
    Owners.hasMany(models.Pets, { 
     onDelete: "cascade" 
    }); 
}; 
Owners.associate = function(models) { 
    Owners.hasMany(models.Posts, { 
     onDelete: "cascade" 
    }); 
}; 

,但我一直在獲取錯誤,其中一個表中沒有關聯到Owners表。有沒有更好的方式使這種關聯起作用?

回答

0

您只需在擁有者模型上使用hasMany,不需要在其他模型上使用belongsTo。當您使用hasMany時,它會在目標模型上創建OwnerId,我建議使用as,因此如果您需要在查詢上執行Include,您可以識別 密鑰。你也可以定義一次關聯功能:

Owners.associate = function(models) { 
    Owners.hasMany(models.Pets, { 
    as: 'OwnerPets', 
    onDelete: "cascade" 
    }); 
    Owners.hasMany(models.Posts, { 
    as: 'OwnerPosts', 
    onDelete: "cascade" 
    }); 
}; 
+0

好的謝謝!會嘗試。 –

相關問題