function fn(fn: string, ...args: unknown[]): Fn;
Creates an object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions. If you want to refer to columns in your function, you should use sequelize.col
, so that the columns are properly interpreted as columns and not a strings.
Sequelize.fn()을 사용하면 SQL 함수(SUM, CONCAT, IFNULL 등)을 쉽게 사용할 수 있다.
첫번째 인자 String은 Parameter로 함수명을, 두 번째 Parameter부터는 대상을 지정하면 된다.
예시를 들면
// SUBSTR(str, pos);
sequelize.fn("substr", str, pos);
// IFNULL(a, b);
sequelize.fn("ifnull", a, b);
// SUM(a, b);
sequelize.fn("sum", a, b);
// CONCAT(a, b);
sequelize.fn("concat", a, b);
또한 COUNT도 나타낼 수 있다
// This is a tiresome way of getting the number of hats (along with every column)
Model.findAll({
attributes: [
'id', 'foo', 'bar', 'baz', 'qux', 'hats', // We had to list all attributes...
[sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats'] // To add the aggregation...
]
});
// This is shorter, and less error prone because it still works if you add / remove attributes from your model later
Model.findAll({
attributes: {
include: [
[sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats']
]
}
});
SQL문으로 나타내면
SELECT id, foo, bar, baz, qux, hats, COUNT(hats) AS n_hats FROM ...
위에서 학습한 Sequelize.fn을 WHERE절에서 사용할 때는 Sequelize.where로 사용할 수 있다.
function where(attr: object, comparator: symbol, logic: string | object):
attr = object : 참조할 객체를 의미