
在我的部落格平台的更新中,我需要添加縮圖列以使文章更具視覺吸引力。此更新伴隨著從在單一頁面上顯示所有文章到在自己的頁面上顯示每一篇文章的轉變,隨著文章數量的增長改進了導航。
縮圖列儲存表示圖像連結的字串。這種方法使資料庫保持輕量級,並透過在其他地方處理影像儲存來分離關注點。
將新列加入模型中
首先,我更新了 BlogPosts 模型以包含縮圖列。設定allowNull: true確保添加縮圖是可選的,並避免了尚未有縮圖的舊帖子的問題:
1 2 3 4 | thumbnail: {
type: DataTypes.STRING,
allowNull: true,
},
|
登入後複製
但是,僅對模型進行這種更改還不夠。 Postgres 資料庫無法辨識新列,我遇到了錯誤:
錯誤:「縮圖」列不存在
發生這種情況是因為 Sequelize 模型定義了應用程式與資料庫的交互方式,但它們不會自動修改資料庫架構。為了解決這個問題,我需要使用 Sequelize 遷移。
準備 Sequelize 進行遷移
在建立遷移之前,我確保 Sequelize CLI 已在專案中初始化。在執行以下命令(這將建立 config/ 資料夾和相關設定)之前,請務必先輸入 npm installsequelize-cli
安裝它
npx Sequelize-cli init
在 config/ 資料夾中,我選擇使用 config.js 檔案而不是 config.json。這允許我使用 dotenv 的環境變數進行設定:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | require ( 'dotenv' ).config();
module.exports = {
development: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: "postgres" ,
},
production: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: "postgres" ,
},
};
|
登入後複製
然後我刪除了 config.json 檔案以避免衝突。
產生遷移文件
接下來,我使用以下命令建立了用於新增縮圖列的移轉檔案:
npx Sequelize-cli 遷移:產生 --name add-thumbnail-to-blogposts
這會在migrations/資料夾中建立一個新文件,命名如下:
20241206232526-add-thumbnail-to-blogposts.js
我修改了此文件以新增列:
1 2 3 4 5 6 7 8 9 10 11 12 | module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.addColumn( 'blogposts' , 'thumbnail' , {
type: Sequelize.STRING,
allowNull: true,
});
},
down: async (queryInterface) => {
await queryInterface.removeColumn( 'blogposts' , 'thumbnail' );
},
};
|
登入後複製
應用遷移
為了更新開發資料庫,我執行了以下命令:
npx Sequelize-cli db:migrate
這成功地將縮圖列添加到部落格文章表中,使我能夠儲存每篇文章的圖像連結。
在生產中應用遷移
對於資料庫的部署版本,我按照以下步驟操作:
1 2 3 4 | Backup the Production Database: Before making changes, I downloaded a backup to safeguard against misconfigurations.
Copy the Migration Files: I ensured the updated config.js file and add-thumbnail-to-blogposts.js migration file were present in the server repository.
Set Environment Variables: I verified that the production environment variables required by dotenv were configured correctly. These were set in the Setup Node.js App section of cPanel.
Run the Migration: I navigated to the backend app directory in the production terminal and ran:
|
登入後複製
npx Sequelize-cli db:migrate --env production
這成功地將縮圖列新增至生產 Postgres 資料庫。
結論
新增縮圖列可以顯示每篇部落格文章的圖像,增強了平台的視覺吸引力和可用性。這些步驟提供了一種結構化且可重複的方法,用於使用 Sequelize 遷移向資料庫新增列,這對於維持模型和資料庫之間的同步至關重要。
以上是使用 Sequelize 遷移新增列的步驟的詳細內容。更多資訊請關注PHP中文網其他相關文章!