diff --git a/src/index.js b/src/index.js index 12c9c20..a6787fb 100644 --- a/src/index.js +++ b/src/index.js @@ -1,6 +1,7 @@ const Builder = require('./builder'); const Model = require('./model'); +const Pivot = require('./pivot'); const Collection = require('./collection'); const Paginator = require('./paginator'); const sutando = require('./sutando'); @@ -18,6 +19,7 @@ module.exports = { Paginator, Collection, Model, + Pivot, Builder, Attribute, CastsAttributes, diff --git a/src/model.js b/src/model.js index 82f1c5e..a7d2230 100644 --- a/src/model.js +++ b/src/model.js @@ -490,7 +490,7 @@ class Model extends BaseModel { } newPivot(parent, attributes, table, exists, using = null) { - return using ? using.constructor.fromRawAttributes(parent, attributes, table, exists) + return using ? using.fromRawAttributes(parent, attributes, table, exists) : Pivot.fromAttributes(parent, attributes, table, exists); } diff --git a/src/relations/belongs-to-many.js b/src/relations/belongs-to-many.js index 9267487..bd3ab64 100644 --- a/src/relations/belongs-to-many.js +++ b/src/relations/belongs-to-many.js @@ -108,6 +108,20 @@ class BelongsToMany extends compose( return new Collection(models); } + async first(columns = ['*']) { + const results = await this.take(1).get(columns); + return results.count() > 0 ? results.first() : null; + } + + async firstOrFail(columns = ['*']) { + const model = await this.first(columns); + if (model !== null) { + return model; + } + + throw (new ModelNotFoundError).setModel(this.related.constructor); + } + async paginate(page = 1, perPage = 15, columns = ['*']) { this.query.select(this.shouldSelect(columns)); @@ -116,11 +130,28 @@ class BelongsToMany extends compose( }); } + async chunk(count, callback) { + return await this.prepareQueryBuilder().chunk(count, async (results, page) => { + this.hydratePivotRelation(results.all()); + + return await callback(results, page); + }); + } + + setUsing(model) { + this.using = model; + return this; + } + as(accessor) { this.accessor = accessor; return this; } + prepareQueryBuilder() { + return this.query.select(this.shouldSelect()); + } + hydratePivotRelation(models) { models.map(model => { model.setRelation(this.accessor, this.newExistingPivot( diff --git a/sutando.mjs b/sutando.mjs index 190e476..1384be0 100644 --- a/sutando.mjs +++ b/sutando.mjs @@ -5,6 +5,7 @@ const { Paginator, Collection, Model, + Pivot, Builder, Attribute, CastsAttributes, @@ -33,6 +34,7 @@ export { Paginator, Collection, Model, + Pivot, Builder, Attribute, CastsAttributes,