From c57e6122862e7dfe3de0b58513db713947175e43 Mon Sep 17 00:00:00 2001 From: Fabien O'Carroll Date: Thu, 24 Jun 2021 10:42:39 +0100 Subject: [PATCH] Added benefits relation to Product model refs https://github.com/TryGhost/Team/issues/806 This relation sets up the ability to both read and write relations via the Product model, allowing us to expose benefits via the Admin Product API. --- core/server/models/product.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/core/server/models/product.js b/core/server/models/product.js index 4a88eca651..d17e8ae3e4 100644 --- a/core/server/models/product.js +++ b/core/server/models/product.js @@ -4,6 +4,12 @@ const _ = require('lodash'); const Product = ghostBookshelf.Model.extend({ tableName: 'products', + relationships: ['benefits'], + + relationshipBelongsTo: { + benefits: 'benefits' + }, + async onSaving(model, _attr, options) { ghostBookshelf.Model.prototype.onSaving.apply(this, arguments); @@ -78,6 +84,17 @@ const Product = ghostBookshelf.Model.extend({ return filteredKeys; }, + benefits() { + return this.belongsToMany('Benefit', 'products_benefits', 'product_id', 'benefit_id') + .withPivot('sort_order') + .query('orderBy', 'sort_order', 'ASC') + .query((qb) => { + // avoids bookshelf adding a `DISTINCT` to the query + // we know the result set will already be unique and DISTINCT hurts query performance + qb.columns('benefits.*'); + }); + }, + monthlyPrice() { return this.belongsTo('StripePrice', 'monthly_price_id', 'id'); },