bookshelf.js 的多个多对多关系
multiple many to many relationships with bookshelf.js
我正在尝试确定使用 Bookshelf.js 表示以下内容的最佳方式:
我有一个 Appointment
模型,每个 Appointment
有:
- 1 个或更多
Pet
(s)
- 1 个或更多
Service
(s)
我可以使用 Bookshelf 中的多对多关系轻松表示这一点,这会生成三个表:appointment
、appointment_pet
和 appointment_service
。
我现在有一个新要求,要求能够在每个约会的基础上指定与每个 Pet
关联的 Service
(s),以便与特定关联的服务宠物可能很容易被找回。例如:
约会 1
- 有 1 只宠物
- 有 2 项服务(
walk
、water plants
)
- 宠物仅与
walk
服务关联。
获取与 Appointment 1
关联的 Pet
的所有服务将 return walk
.
是否有使用 Bookshelf 表示此场景的最佳方式?
我在考虑任何 Pet
总是与 Service
关联。在那种情况下,我会像这样构造它:
例如,Service
模型充当 Appointment
和 Pet
之间的桥梁。 Service
可以有宠物(例如当它是 walk
时)或没有(例如当它是 water plants
时)。 BookshelfJS 模型看起来像:
var Appointment = bookshelf.Model.extend({
services: function () {
return this.hasMany('Service');
},
pets: function () {
return this.hasMany('Pet').through('Service');
},
});
一个可能的问题是您最终会得到许多相同类型的不同 Service
,但是 Appointment
和 Pet
的不同组合。如果 Service
上的属性不多,这没有问题。例如,如果 Service
只有一个 type
属性。
如果您想向 Service
添加更多属性,例如 price
、time_duration
等,您可以将其提取到自己的 table 中,如:
然后 Service
table 将具有每种类型的服务及其属性(例如 price
、time_duration
、...)。代码如下所示:
var Appointment = bookshelf.Model.extend({
services: function () {
return this.hasMany('Service').through('AppointmentService');
},
pets: function () {
return this.hasMany('Pet').through('AppointmentService');
},
});
我建议使用更简单的案例,然后根据需要进行更改。您可能还需要使用 withPivot 方法从关系 tables.
中获取值
我正在尝试确定使用 Bookshelf.js 表示以下内容的最佳方式:
我有一个 Appointment
模型,每个 Appointment
有:
- 1 个或更多
Pet
(s) - 1 个或更多
Service
(s)
我可以使用 Bookshelf 中的多对多关系轻松表示这一点,这会生成三个表:appointment
、appointment_pet
和 appointment_service
。
我现在有一个新要求,要求能够在每个约会的基础上指定与每个 Pet
关联的 Service
(s),以便与特定关联的服务宠物可能很容易被找回。例如:
约会 1
- 有 1 只宠物
- 有 2 项服务(
walk
、water plants
) - 宠物仅与
walk
服务关联。
获取与 Appointment 1
关联的 Pet
的所有服务将 return walk
.
是否有使用 Bookshelf 表示此场景的最佳方式?
我在考虑任何 Pet
总是与 Service
关联。在那种情况下,我会像这样构造它:
例如,Service
模型充当 Appointment
和 Pet
之间的桥梁。 Service
可以有宠物(例如当它是 walk
时)或没有(例如当它是 water plants
时)。 BookshelfJS 模型看起来像:
var Appointment = bookshelf.Model.extend({
services: function () {
return this.hasMany('Service');
},
pets: function () {
return this.hasMany('Pet').through('Service');
},
});
一个可能的问题是您最终会得到许多相同类型的不同 Service
,但是 Appointment
和 Pet
的不同组合。如果 Service
上的属性不多,这没有问题。例如,如果 Service
只有一个 type
属性。
如果您想向 Service
添加更多属性,例如 price
、time_duration
等,您可以将其提取到自己的 table 中,如:
然后 Service
table 将具有每种类型的服务及其属性(例如 price
、time_duration
、...)。代码如下所示:
var Appointment = bookshelf.Model.extend({
services: function () {
return this.hasMany('Service').through('AppointmentService');
},
pets: function () {
return this.hasMany('Pet').through('AppointmentService');
},
});
我建议使用更简单的案例,然后根据需要进行更改。您可能还需要使用 withPivot 方法从关系 tables.
中获取值