Skip to content

Commit

Permalink
fix: first method in belongsToMany relation
Browse files Browse the repository at this point in the history
  • Loading branch information
kiddyuchina committed Sep 15, 2024
1 parent 036abcd commit 6f64a01
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -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');
Expand All @@ -18,6 +19,7 @@ module.exports = {
Paginator,
Collection,
Model,
Pivot,
Builder,
Attribute,
CastsAttributes,
Expand Down
2 changes: 1 addition & 1 deletion src/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
31 changes: 31 additions & 0 deletions src/relations/belongs-to-many.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand All @@ -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(
Expand Down
2 changes: 2 additions & 0 deletions sutando.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const {
Paginator,
Collection,
Model,
Pivot,
Builder,
Attribute,
CastsAttributes,
Expand Down Expand Up @@ -33,6 +34,7 @@ export {
Paginator,
Collection,
Model,
Pivot,
Builder,
Attribute,
CastsAttributes,
Expand Down

0 comments on commit 6f64a01

Please sign in to comment.