mirror of
https://github.com/TryGhost/Ghost.git
synced 2024-12-25 03:44:29 +03:00
4fe417bcab
refs https://github.com/TryGhost/Team/issues/586 We have to use `belongsToMany` because of the way bookshelf relations work. In reality the relationship is 'hasMany', e.g. a Product has many Stripe Prices. These relations are the minimal needed to satisfy the following relationships without transforming the results. (e.g. flattening the StripePrices from a list of StripeProducts for a Product) Product -> StripeProduct: product.related('stripeProducts') StripeProduct -> StripePrice: stripeProduct.related('stripePrices'); Product -> StripePrice: product.related('stripePrices'); StripePrice -> Product: stripePrice.related('stripeProduct.product');
56 lines
1.4 KiB
JavaScript
56 lines
1.4 KiB
JavaScript
const ghostBookshelf = require('./base');
|
|
|
|
const Product = ghostBookshelf.Model.extend({
|
|
tableName: 'products',
|
|
|
|
async onSaving(model, _attr, options) {
|
|
ghostBookshelf.Model.prototype.onSaving.apply(this, arguments);
|
|
|
|
if (model.get('name')) {
|
|
model.set('name', model.get('name').trim());
|
|
}
|
|
|
|
if (model.hasChanged('slug') || !model.get('slug')) {
|
|
const slug = model.get('slug') || model.get('name');
|
|
|
|
if (!slug) {
|
|
return;
|
|
}
|
|
|
|
const cleanSlug = await ghostBookshelf.Model.generateSlug(Product, slug, {
|
|
transacting: options.transacting
|
|
});
|
|
|
|
return model.set({slug: cleanSlug});
|
|
}
|
|
},
|
|
|
|
stripeProducts() {
|
|
return this.hasMany('StripeProduct', 'product_id', 'id');
|
|
},
|
|
|
|
stripePrices() {
|
|
return this.belongsToMany(
|
|
'StripePrice',
|
|
'stripe_products',
|
|
'product_id',
|
|
'stripe_product_id',
|
|
'id',
|
|
'stripe_product_id'
|
|
);
|
|
},
|
|
|
|
members() {
|
|
return this.belongsToMany('Member', 'members_products', 'product_id', 'member_id');
|
|
}
|
|
});
|
|
|
|
const Products = ghostBookshelf.Collection.extend({
|
|
model: Product
|
|
});
|
|
|
|
module.exports = {
|
|
Product: ghostBookshelf.model('Product', Product),
|
|
Products: ghostBookshelf.collection('Products', Products)
|
|
};
|