簡體   English   中英

BelongsTo/HasOne 關聯是否意味着 BelongsTo 的 Model 必須始終具有關聯的 Model?

[英]Does a BelongsTo/HasOne Association mean the Model that BelongsTo the other must always have an associated Model?

給定模型“Animal”和“Person”,其中 Animal BelongsTo Person 和 Person HasOne Animal,這是否意味着每個 Animal 實例都將始終有一個與 Animal 關聯的 Person 實例(由於 Animal Belonging To Person)? 反過來,這是否意味着不是每個 Person 實例都會有一個與之關聯的 Animal 實例(由於 Person有一個Animal)?

例如:

const sequelize = new Sequelize()
const Person = sequelize.define('Person', {
  id: {
    type: DataTypes.UUID,
    primaryKey: true,
    defaultValue: DataTypes.UUIDV4,
  },
})

const Animal = sequelize.define('Animal', {
  id: {
    type: DataTypes.UUID,
    primaryKey: true,
    defaultValue: DataTypes.UUIDV4,
  },
})

Person.hasOne(Animal)
Animal.belongsTo(Person)

async function foo () {
  const animals = await Animal.findAll()
  for (const animal of animals) {
    /**
     * Can I be certain that `person` **always** exists, given that Animal BelongsTo Person?
     * 
     * In other words, does the BelongsTo Association from Animal to Person imply that Animal
     * must **always** have a Person associated with the Animal?
     */
    const person = await animal.getPerson()
  }
  
  const people = await Person.findAll()
  for (const person of people) {
    /**
     * And the inverse; given that Person hasOne Animal, does this imply that not all People
     * will have an Animal associated with them?
     */
    const animal = await person.getAnimal()
  }
}

我發現一些與我的問題相關的文檔讓我感到困惑:

原則上,這兩個選項都是在 Foo 和 Bar 之間建立一對一關系的有效方式。 然而,當我們說“Foo 和 Bar 之間存在一對一的關系”時,並不清楚這種關系是強制性的還是可選的。 換句話說,Foo 可以沒有 Bar 存在嗎? Bar 可以沒有 Foo 嗎? 這些問題的答案有助於確定我們希望外鍵列位於何處。

文檔中的這段摘錄讓我認為屬於另一個 model 的任何 model 必須始終具有與之關聯的另一個 model 的實例,而相反,具有另一個 model 的任何 model 有時不會與另一個 8588 關聯 it3689570588 的實例.

假設Person有一輛CarCar屬於Person 這意味着您可以在Cat表中看到引用該人員 ID 的 FK。

在sequelize中,你定義的“hasOne”和“belongsTo”的目的是讓你在Model查詢中做一些SQL以PersonCar為主題的查詢

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM