* Count the number of records matching the provided where clause. * * If you provide an `include` option, the number of matching associations will be counted instead. * * @param {object} [options] options * @param {object} [options.where] A hash of search attributes.
(options)
| 2089 | * @returns {Promise<number>} |
| 2090 | */ |
| 2091 | static async count(options) { |
| 2092 | options = Utils.cloneDeep(options); |
| 2093 | options = _.defaults(options, { hooks: true }); |
| 2094 | |
| 2095 | // Add CLS transaction |
| 2096 | if (options.transaction === undefined && this.sequelize.constructor._cls) { |
| 2097 | const t = this.sequelize.constructor._cls.get('transaction'); |
| 2098 | if (t) { |
| 2099 | options.transaction = t; |
| 2100 | } |
| 2101 | } |
| 2102 | |
| 2103 | options.raw = true; |
| 2104 | if (options.hooks) { |
| 2105 | await this.runHooks('beforeCount', options); |
| 2106 | } |
| 2107 | let col = options.col || '*'; |
| 2108 | if (options.include) { |
| 2109 | col = `${this.name}.${options.col || this.primaryKeyField}`; |
| 2110 | } |
| 2111 | if (options.distinct && col === '*') { |
| 2112 | col = this.primaryKeyField; |
| 2113 | } |
| 2114 | options.plain = !options.group; |
| 2115 | options.dataType = new DataTypes.INTEGER(); |
| 2116 | options.includeIgnoreAttributes = false; |
| 2117 | |
| 2118 | // No limit, offset or order for the options max be given to count() |
| 2119 | // Set them to null to prevent scopes setting those values |
| 2120 | options.limit = null; |
| 2121 | options.offset = null; |
| 2122 | options.order = null; |
| 2123 | |
| 2124 | const result = await this.aggregate(col, 'count', options); |
| 2125 | |
| 2126 | // When grouping is used, some dialects such as PG are returning the count as string |
| 2127 | // --> Manually convert it to number |
| 2128 | if (Array.isArray(result)) { |
| 2129 | return result.map(item => ({ |
| 2130 | ...item, |
| 2131 | count: Number(item.count) |
| 2132 | })); |
| 2133 | } |
| 2134 | |
| 2135 | return result; |
| 2136 | } |
| 2137 | |
| 2138 | /** |
| 2139 | * Find all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very useful for paging |