Sails基础之Models层的Associations

本文深入探讨了Sails.js框架中的ORM关联机制,包括一对一、一对多及多对多关联的具体实现方式,并通过实例展示了如何在Model间建立关联。

Sails提供了ORM,Model间的关联通过ORM完成,Sails的文档(https://sailsjs.com/documentation/concepts/models-and-orm)
中给出了详细的案例,我们这里给出常见三类关联的具体案例。

One-to-one


上面ER图中给出了一个One-to-one的关系模型,对应的Model代码如下:
Owner Model:

module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    age: {
      type: 'number'
    },
    pet: {
      model: 'pet'
    }
  }
};

Pet Model:

module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    color: {
      type: 'string'
    },
    owner: {
      model: 'user'
    }
  }
  
};

可以看到,One的关系主要可以通过建立关联属性中的model进行关联指向,进行测试过程如下:
http://localhost:1337/owner/create?name=foo&age=18
http://localhost:1337/pet/create?name=cat&color=red&owner=1
http://localhost:1337/owner/update/1?pet=1
执行完成后,验证结果:

通过http://localhost:1337/owner/find/1和http://localhost:1337/pet/find/1检查ORM的结果:

One-to-many

图片.png
上面ER图中给出了一个One-to-many的关系模型,对应的Model代码如下:
Owner Model:

module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    age: {
      type: 'number'
    },
    pets: {
      collection: 'pet',
      via: 'owner'
    }
  }
};

Pet Model:

module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    color: {
      type: 'string'
    },
    owner: {
      model: 'owner'
    }
  }
  
};

可以看到,Many的关系主要可以通过建立关联属性中的collection并指定关联属性名称方式进行关联指向,进行测试过程如下:
http://localhost:1337/owner/create?name=foo&age=18
http://localhost:1337/pet/create?name=cat&color=red&owner=1
http://localhost:1337/pet/create?name=dog&color=red&owner=1
执行完成后,验证结果:

可以看到Owner Model中的pets属性只是一个虚拟的属性,专用于ORM操作。

通过http://localhost:1337/owner/find/1http://localhost:1337/pet/find/1检查ORM的结果:


Many-to-many

上面ER图中给出了一个Many-to-many的关系模型,对应的Model代码如下:
Owner Model:

module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    age: {
      type: 'number'
    },
    pets: {
      collection: 'pet',
      via: 'owners'
    }
  }
};

Pet Model:

module.exports = {
  attributes: {
    name: {
      type: 'string'
    },
    color: {
      type: 'string'
    },
    owners: {
      collection: 'owner',
      via: 'pets'
    }
  }
  
};

可以看到,Many-to-many的关系完全是关系两边Model通过collection方式进行互相引用关联的,在进行关联是需要使用Waterline中提供的addToCollection方法进行操作,这个后面再详细介绍。
我们现在只验证结果:

可以看到,Sails已经根据配置自动建出了用于Many-to-many关联的中间表。
你也可以自己指定中间表,参考:
https://sailsjs.com/documentation/concepts/models-and-orm/associations/through-associations

跨适配器关联

由于Sails提供了Waterline特性,将不同Adapter的主要api进行了统一抽象,并且提供了跨适配器创建Model,因此,还提供了跨适配器关联的神技,可以参考:
https://sailsjs.com/documentation/concepts/models-and-orm/associations(Cross-adapter associations)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值