我使用 ORM Sequelize 定义了 Customer 表和 Address 表之间的一对一关系
Customer.js源码如下:
// One to One Relationship
// Customer.js
// Include Sequelize module.
const Sequelize = require('sequelize');
const Datatypes = require('Sequelize');
const path = require("path");
// Import sequelize object,
// Database connection pool managed by Sequelize.
// Import db_sequelize
const db_sequelize = require(path.join(__dirname,'..','config','db_sequelize.js'));
const Customer = db_sequelize.define('Customer', {
customer_id:{
// Sequelize module has INTEGER Data_Type.
type:Datatypes.INTEGER,
// To increment user_id automatically.
autoIncrement:true,
// user_id can not be null.
allowNull:false,
// For uniquely identify user.
primaryKey:true
},
first_name: { type: Datatypes.STRING, allowNull:true },
last_name: { type: Datatypes.STRING, allowNull:true },
email: { type: Datatypes.STRING, allowNull:true},
address_id: { type: Datatypes.INTEGER, allowNull:true},
// dates => current time
myDate: { type: Datatypes.DATE,
defaultValue: Sequelize.NOW },
// Timestamps
createdAt: Datatypes.DATE,
updatedAt: Datatypes.DATE,
});
// Exporting Customer, using this constant
// we can perform CRUD operations on
// 'Customer' table.
console.log(Date() + " " + "Model Customer has been defined");
module.exports = Customer;
Address.js源码如下:
// Address.js
// Include Sequelize module.
const Sequelize = require('sequelize');
const Datatypes = require('sequelize');
const path = require("path");
// Import sequelize object,
// Database connection pool managed by Sequelize.
// Import db_sequelize
const db_sequelize = require(path.join(__dirname,'..','config','db_sequelize.js'));
const Address = db_sequelize.define('Address', {
address_id:{
// Sequelize module has INTEGER Data_Type.
type:Datatypes.INTEGER,
// To increment user_id automatically.
autoIncrement:true,
// user_id can not be null.
allowNull:false,
// For uniquely identify user.
primaryKey:true
},
address: { type: Datatypes.STRING, allowNull:true },
postal_code: { type: Datatypes.STRING, allowNull:true },
district: { type: Datatypes.STRING, allowNull:true},
// dates => current time
myDate: { type: Datatypes.DATE,
defaultValue: Datatypes.NOW },
// Timestamps
createdAt: Datatypes.DATE,
updatedAt: Datatypes.DATE,
});
const Customer = require(path.join(__dirname,'..','models', 'Customer.js'));
// 1:1 Relation between Customer and Address
// Each Customer has only One Address
Customer.hasOne(Address, {
foreignKey: {
name: 'address_id'
}
});
Address.belongsTo(Customer, {
foreignKey: 'address_id'
});
// Exporting Address, using this constant
// we can perform CRUD operations on
// 'Address' table.
console.log(Date() + " " + "Model Address has been defined");
module.exports = Address;
显示与客户关联的地址值时,无需使用 .ejs 模板即可正确显示地址
// TEST ONE TO ONE RELATIONSHIP
// Get Customer address for customer_id equal 1
let get_address_customer_id = async function(){
try {
let customer = await Customer.findByPk(1);
// find by primary key
let customerAddress = await customer.getAddress();
//Address belongs to Customer
//then customer.getAddress();
//get the address
//for customer_id equal 1
console.log("NUI del Customer : ", customer.customer_id);
console.log("Customer Name : ", customer.first_name + " " + customer.last_name);
console.log("Customer Address : ", customerAddress.address);
} catch (error) { console.error("Error log", error);}
}
get_address_customer_id();
NUI 客户:1
客户姓名:名字 1 姓氏 1
客户地址:地址1
但是,使用 .ejs 模板时,客户和地址之间的一对一关系不起作用。在一对一关系测试中,我使用 let customerAddress = wait customer.getAddress();但是,我不在 .ejs 模板中使用它,我认为这就是区别。但是,假设如果 1 对 1 关系有效,您应该获得链接到客户的地址
// list_customers.js
// Set router
const express = require("express");
const router = express.Router();
const path = require("path");
router.get("/", async (req, res) => {
//Get the model for Customer
const Customer = require(path.join(__dirname,'..', 'models', 'Customer.js'));
// Find all Customers
const customers = await Customer.findAll();
res.render("view_listar_customers.ejs", { model: customers });
});
module.exports = router;
显示Customer和Address关系数据的.ejs模板代码如下:
<tbody>
<% for (const customer of model) { %>
<tr>
<td><%= customer.customer_id %></td>
<td><%= customer.first_name %>, <%= customer.last_name %></td>
<td><%= customer.address %></td>
<td class="d-print-none">
<a class="btn btn-sm btn-warning" href="/edit_customer/<%= customer.customer_id %>">Edit</a>
<a class="btn btn-sm btn-danger" href="/delete_customer/<%= customer.customer_id %>">Delete</a>
</td>
</tr>
<% } %>
</tbody>
解决问题的指南将不胜感激。谢谢你。
我找到了使用 Sequelize 的原始查询来显示数据的替代方法。我附上了源代码部分,以防对于想要使用 ORM Sequelize 的一对一关系显示所有记录的查询结果并将结果显示在 .ejs 模板中的人有用。
router.get("/", async (req, res) => {
//Get the model for Customer and Address
const Customer = require(path.join(__dirname,'..', 'models', 'Customer.js'));
const Address = require(path.join(__dirname,'..', 'models', 'Address.js'));
const db_sequelize = require(path.join(__dirname, '..','config', 'db_sequelize.js'));
// Inner Join
const [customers, metadata] = await db_sequelize.query(
"SELECT C.first_name, C.last_name, A.address FROM Customer C INNER JOIN Address A ON C.AddressId=A.id");
// Display Clients with their addresses
res.render("view_listar_customers.ejs", { model: customers });
});