[英]Trying to join parent / primary table to child / foreign table in sequelize
我試圖從文章表中獲取我所有的文章數據,但也試圖從我制作的用戶表中獲取用戶數據。 我使用 sequelize 將數據庫構建到 MySQL 數據庫以及 ORM,這是代碼片段
用戶表
const User = sequelize.define('users', ({
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
nama: {
type: DataTypes.STRING(50),
allowNull: false,
},
email: {
type: DataTypes.STRING(50),
allowNull: false,
},
password: {
type: DataTypes.STRING(50),
allowNull: false,
}
}))
物品代碼
const Articles = sequelize.define('articles', ({
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
description: {
type: DataTypes.TEXT,
allowNull: false
},
gambar: {
type: DataTypes.STRING,
allowNull: false
},
userId: {
type: DataTypes.BIGINT,
allowNull: false,
}
}))
關系
User.hasMany(Articles, {
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
})
Articles.belongsTo(User, {
foreignKey: 'userId'
})
我試過的 ORM
Articles.findAll({
include: [User]
})
總是返回 users 表未關聯到 artiles
在創建關系期間,您必須使用 as 關鍵字。
Articles.belongsTo(User, {
as: 'user',
foreignKey: 'userId'
})
然后更新表格
Articles.findAll({include: [{
model: model.User,
as: 'user'
}]})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.