新聞中心
在egg中,可以使用mysql的LIKE關鍵字進行模糊查詢,SELECT * FROM table WHERE column LIKE '%keyword%'。
在Egg.js中,我們可以使用Sequelize庫來操作MySQL數(shù)據(jù)庫,以下是如何在Egg.js中使用Sequelize進行模糊查詢的詳細步驟:

創(chuàng)新互聯(lián)建站-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設、高性價比華容網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式華容網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設找我們,業(yè)務覆蓋華容地區(qū)。費用合理售后完善,10余年實體公司更值得信賴。
1、安裝Sequelize和mysql2模塊
我們需要安裝Sequelize和mysql2模塊,在項目根目錄下運行以下命令:
npm install sequelize mysql2 save
2、配置數(shù)據(jù)庫連接
在config/config.default.js文件中,配置數(shù)據(jù)庫連接信息:
exports.sequelize = {
client: 'mysql',
connection: {
host: '127.0.0.1',
port: '3306',
user: 'root',
password: 'your_password',
database: 'your_database'
},
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
3、創(chuàng)建模型
在項目中創(chuàng)建一個名為app/model的文件夾,然后在該文件夾中創(chuàng)建一個名為user.js的文件,用于定義用戶模型:
// app/model/user.js
const Sequelize = require('sequelize');
const sequelize = require('../config/config').sequelize;
const User = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: Sequelize.STRING,
email: Sequelize.STRING,
age: Sequelize.INTEGER
}, {
tableName: 'users'
});
module.exports = User;
4、進行模糊查詢
在需要執(zhí)行模糊查詢的地方,引入User模型并執(zhí)行查詢,在app/controller/user.js文件中,我們可以編寫一個根據(jù)用戶名模糊查詢用戶的控制器:
// app/controller/user.js
const Controller = require('egg').Controller;
const User = require('../model/user');
class UserController extends Controller {
async search() {
const { ctx } = this;
const keyword = ctx.query.keyword || ''; // 獲取查詢參數(shù)中的關鍵字,如果沒有則默認為空字符串
const users = await User.findAll({ // 使用Sequelize的findAll方法進行模糊查詢,其中包含一個where對象,用于指定查詢條件
where: {
name: { [Sequelize.Op.like]: %${keyword}% } // 使用Sequelize的Op對象的like方法進行模糊匹配,將關鍵字用百分號包圍,表示任意字符出現(xiàn)任意次數(shù)
}
});
ctx.body = users; // 返回查詢結果
}
}
module.exports = UserController;
5、測試模糊查詢功能
啟動項目后,訪問http://localhost:7001/api/user/search?keyword=張,將會返回所有名字中包含“張”的用戶信息。
分享題目:egg中mysql如何模糊查詢
URL分享:http://www.dlmjj.cn/article/djisohe.html


咨詢
建站咨詢
