BelongsToMany
繼承自
使用連接表的 多對多 關聯。
當連接表有額外的屬性時,可以將這些屬性傳遞到選項物件中
UserProject = sequelize.define('user_project', {
role: Sequelize.STRING
});
User.belongsToMany(Project, { through: UserProject });
Project.belongsToMany(User, { through: UserProject });
// through is required!
user.addProject(project, { through: { role: 'manager' }});
所有方法都允許您傳遞已持久化的實例、其主鍵或兩者的混合
const project = await Project.create({ id: 11 });
await user.addProjects([project, 12]);
如果您想設置多個目標實例,但具有不同的屬性,您必須在實例上設置屬性,使用一個名稱為 through 模型的屬性
p1.UserProjects = {
started: true
}
user.setProjects([p1, p2], { through: { started: false }}) // The default value is false, but p1 overrides that.
同樣地,當通過具有自訂屬性的連接表獲取資料時,這些屬性將以 through 模型名稱的物件形式提供。
const projects = await user.getProjects();
const p1 = projects[0];
p1.UserProjects.started // Is this project started yet?
在下面的 API 參考中,將關聯的名稱添加到方法中,例如,對於 User.belongsToMany(Project)
,getter 將會是 user.getProjects()
。
方法摘要
公開方法 | ||
公開 |
async add(sourceInstance: Model, newInstances: Model | Model[] | string[] | string | number[] | number, options: object): Promise 將一個或多個資料列與來源實例關聯。 |
|
公開 |
計算目前與此關聯的所有內容,使用可選的 where 子句。 |
|
公開 |
建立關聯模型的新實例,並將其與此關聯。 |
|
公開 |
取得目前與此關聯的所有內容,使用可選的 where 子句。 |
|
公開 |
async has(sourceInstance: Model, instances: Model | Model[] | string[] | string | number[] | number, options: object): Promise<boolean> 檢查一個或多個實例是否與此關聯。 |
|
公開 |
remove(sourceInstance: Model, oldAssociatedObjects: Model | Model[] | string | string[] | number | number[], options: object): Promise 取消關聯一個或多個實例。 |
|
公開 |
async set(sourceInstance: Model, newAssociatedObjects: Model | Model[] | string[] | string | number[] | number, options: object): Promise 通過傳遞實例或其主鍵的數組來設置關聯的模型。 |
繼承的摘要
來自類別 Association | ||
公開 |
關聯的類型。 |
|
公開 |
|
|
公開 |
|
公開方法
公開 async add(sourceInstance: Model, newInstances: Model | Model[] | string[] | string | number[] | number, options: object): Promise 原始碼
將一個或多個資料列與來源實例關聯。它不會取消關聯任何已經關聯的實例,這些實例可能在 newInstances
中遺失。
公開 async create(sourceInstance: Model, values: object, options: object): Promise 原始碼
建立關聯模型的新實例,並將其與此關聯。
公開 async get(instance: Model, options: object): Promise<Array<Model>> 原始碼
取得目前與此關聯的所有內容,使用可選的 where 子句。
參數
名稱 | 類型 | 屬性 | 描述 |
instance | Model | instance |
|
options | object |
|
查找選項 |
options.where | object |
|
用於限制關聯模型的可選 where 子句 |
options.scope | string | boolean |
|
將範圍應用於相關模型,或通過傳遞 false 來移除其預設範圍 |
options.schema | string |
|
將綱要應用於相關模型 |
options.through.where | object |
|
應用於 through 模型(連接表)的可選 where 子句 |
options.through.paranoid | boolean |
|
如果為 true,則只會從連接表返回未刪除的記錄。如果為 false,則會返回已刪除和未刪除的記錄。僅當 through 模型是 paranoid 時才適用 |
請參閱
- 關於選項的完整說明,請參閱 Model
public async has(sourceInstance: Model, instances: Model | Model[] | string[] | string | number[] | number, options: object): Promise<boolean> 原始碼
檢查一個或多個實例是否與此關聯。如果傳遞實例列表,則當所有實例都關聯時,函數返回 true。
public remove(sourceInstance: Model, oldAssociatedObjects: Model | Model[] | string | string[] | number | number[], options: object): Promise 原始碼
取消關聯一個或多個實例。