Raw queries原始查詢
就是使用了原始的查詢語句,如UPDATE users SET y = 42 WHERE x = 12
As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can utilize the function sequelize.query
.
當經常有使用更簡單的執行原始/已經准備好的SQL查詢的情況出現時,你可以使用函數sequelize.query
。
By default the function will return two arguments - a results array, and an object containing metadata (affected rows etc.). Note that since this is a raw query, the metadata (property names etc.) is dialect specific. Some dialects return the metadata "within" the results object (as properties on an array). However, two arguments will always be returned, but for MSSQL and MySQL it will be two references to the same object.
默認函數將返回兩個參數-一個結果數組和一個包含元數據(被影響的行等數據)的對象。記住因為這是一個原始查詢,元數據(屬性名等)使用的語言是指定的。一些語言返回的元數據帶有結果對象(像數組中的屬性)。可是兩個參數總是被返回的,但是對於MSSQL and MySQL來說這兩個參數將是同個對象的兩個引用
sequelize.query("UPDATE users SET y = 42 WHERE x = 12").spread((results, metadata) => { // Results will be an empty array and metadata will contain the number of affected rows. })
In cases where you don't need to access the metadata you can pass in a query type to tell sequelize how to format the results. For example, for a simple select query you could do:
在這個例子中,你不需要訪問元數據,你可以傳遞一個查詢類型去告訴sequelize怎樣格式化結果。比如下面的簡單select查詢:
sequelize.query("SELECT * FROM `users`", { type: sequelize.QueryTypes.SELECT}) .then(users => { // We don't need spread here, since only the results will be returned for select queries })
Several other query types are available. Peek into the source for details
其他的查詢類型也是可用的
A second option is the model. If you pass a model the returned data will be instances of that model.
模型的第二個選項。如果你在第二個選項中傳遞的是模型,那么返回數據將是模型的實例
// Callee is the model definition. This allows you to easily map a query to a predefined model sequelize.query('SELECT * FROM projects', { model: Projects }).then(projects => { // Each record will now be a instance of Project })
Replacements
Replacements in a query can be done in two different ways, either using named parameters (starting with :
), or unnamed, represented by a ?
. Replacements are passed in the options object.
在查詢中替代能夠以兩種不同方式實現,要么使用命名變量(以:開始),要么不命名,以?來替代。替代將在options對象中被傳遞
- If an array is passed,
?
will be replaced in the order that they appear in the array如果傳遞的是數組,?將會以其出現在數組中的順序被替代 - If an object is passed,
:key
will be replaced with the keys from that object. If the object contains keys not found in the query or vice versa, an exception will be thrown.如果傳遞的是對象,:鍵將被來自對象的鍵值所替代。如果對象包含的鍵在查詢中沒有找到,將拋出一個異常,反之亦然
sequelize.query('SELECT * FROM projects WHERE status = ?', { replacements: ['active'], type: sequelize.QueryTypes.SELECT } ).then(projects => { console.log(projects) }) sequelize.query('SELECT * FROM projects WHERE status = :status ', { replacements: { status: 'active' }, type: sequelize.QueryTypes.SELECT } ).then(projects => { console.log(projects) })
Array replacements will automatically be handled, the following query searches for projects where the status matches an array of values.
數組替代將會自動處理,即下面對對象中status滿足數組值的查詢搜索
sequelize.query('SELECT * FROM projects WHERE status IN(:status) ', { replacements: { status: ['active', 'inactive'] }, type: sequelize.QueryTypes.SELECT } ).then(projects => { console.log(projects) })
To use the wildcard operator %, append it to your replacement. The following query matches users with names that start with 'ben'.
為了使用通配符%並添加其道替代中。以下的查詢匹配名字是以'ben'開始的用戶
sequelize.query('SELECT * FROM users WHERE name LIKE :search_name ', { replacements: { search_name: 'ben%' }, type: sequelize.QueryTypes.SELECT } ).then(projects => { console.log(projects) })
Bind Parameter綁定變量
Bind parameters are like replacements. Except replacements are escaped and inserted into the query by sequelize before the query is sent to the database, while bind parameters are sent to the database outside the SQL query text. A query can have either bind parameters or replacements. Bind parameters are referred to by either $1, $2, ... (numeric) or $key (alpha-numeric). This is independent of the dialect.
綁定變量與替換相似。除了替換是在查詢傳送給數據庫之前通過sequelize進行除去和插入查詢的,而綁定變量是在SQL查詢文本外傳遞給數據庫的。查詢能夠有綁定變量或有替換。綁定變量將通過$1, $2, ... (numeric) 或$key (alpha-numeric)提及。與使用的語言不相關
- If an array is passed,
$1
is bound to the 1st element in the array (bind[0]
)如果傳遞的是數組,$1
將會於數組中的第一個元素(bind[0]
)綁定 - If an object is passed,
$key
is bound toobject['key']
. Each key must begin with a non-numeric char.$1
is not a valid key, even ifobject['1']
exists.如果傳遞的是對象,$key
與object['key']
綁定。每個鍵一定是以非數字字符開始的。$1
不是一個有效鍵,即使object['1']
存在 - In either case
$$
can be used to escape a literal$
sign.在上面兩種情況下,$$
都可以用來轉義字符$
The array or object must contain all bound values or Sequelize will throw an exception. This applies even to cases in which the database may ignore the bound parameter.
數組或對象必須包含所有邊界值,否則Sequelize將拋出異常。這將應用於數據庫可能忽略邊界變量的情況
The database may add further restrictions to this. Bind parameters cannot be SQL keywords, nor table or column names. They are also ignored in quoted text or data. In PostgreSQL it may also be needed to typecast them, if the type cannot be inferred from the context $1::varchar
.
數據庫可能添加更多的限制。綁定變量不能作為SQL的關鍵字,也不能作為表或列名。他們將會在引用文本或數據中被忽略。在PostgreSQL中,如果類型不能從上下文 $1::varchar
中被推導出的話,它可能也需要將他們定型。
sequelize.query('SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $1', { bind: ['active'], type: sequelize.QueryTypes.SELECT } ).then(projects => { console.log(projects) }) sequelize.query('SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $status', { bind: { status: 'active' }, type: sequelize.QueryTypes.SELECT } ).then(projects => { console.log(projects) })