Skip to content
This repository has been archived by the owner on May 7, 2024. It is now read-only.

Latest commit

 

History

History
executable file
·
94 lines (79 loc) · 2.46 KB

OnetoOne.md

File metadata and controls

executable file
·
94 lines (79 loc) · 2.46 KB

一对一

概述

一对一表示的是一个模型只能和另一个模型关联。为了让一个模型知道它相关联的另外一个模型是什么,一个foreign的关键词必须包含在其中的一个记录里并且带有一个unique数据库来约束它。

当前在Waterline中有两种方法来操作这种关联。

Has One Using A Collection

在这个例子中,我们关联一个Pet和一个UserUser只能有一只Pet,反之亦然,一个Pet只能有一个User。然而,为了在这里中双方能够互相查询,我们必须添加一个collection属性到User模型中。这允许我们都可以调用User.find().populate('pet')和Pet.find().populate('owner')`。

这两种方法通过更新Pet模型的owner属性来保持同步。添加unique属性确保每一个owner只有一个值存在于数据库中。当你从User端populate出数据的视乎你将会得到一个数组。

// myApp/api/models/Pet.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    color: {
      type: 'string'
    },
    owner:{
      model:'user',
      unique: true
    }
  }
}
// myApp/api/models/User.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    age: {
      type: 'integer'
    },
    pet: {
      collection:'pet',
      via: 'owner'
    }
  }
}

Has One Manual Sync

在这个例子中,我们关联一个Pet和一个UserUser只能有一只Pet,反之亦然,一个Pet只能有一个User。然而,为了在这里中双方能够互相查询,我们必须添加一个model属性到User模型中。这允许我们都可以调用User.find().populate('pet')和Pet.find().populate('owner')`。

但是这两种模型将不会保持同步。所以当你更新其中一端的时候记得也去更新另外一端。

// myApp/api/models/Pet.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    color: {
      type: 'string'
    },
    owner:{
      model:'user'
    }
  }
}
// myApp/api/models/User.js
module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    age: {
      type: 'integer'
    },
    pet: {
      model:'pet'
    }
  }
}

###注意

关于更细节的描述请参考Waterline Docs