تكملة مثال واحد لواحد - جمعية Nodejs - loizenai.com

جرب أداة القضاء على المشاكل

https://loizenai.com/sequelize-one-to-one-example/

في البرنامج التعليمي ، أقوم بتوجيه كيفية إنشاء نماذج ارتباط مثال واحد إلى واحد Sequelize مع NodeJS / Express ، MySQL.

في البرنامج التعليمي ، أقوم بتوجيه كيفية إنشاء نماذج ارتباط مثال واحد إلى واحد Sequelize مع NodeJS / Express ، MySQL.



  • تقنيات تكملة رابطة Nodejs One to One:
  • Nodejs
  • التعبير
  • تكملة
  • MySQL

تكملة جمعية مثال واحد لواحد

ملحوظة : عند استدعاء طريقة مثل Customer.hasOne(Address) ، نقول إن نموذج العميل هو المصدر ونموذج العنوان هو الهدف.

نحدد نموذجين:

Customer = sequelize.define('customer', { /* attributes */ }); Address = sequelize.define('address', { /* attributes */ });

كيفية إنشاء ارتباط واحد لواحد بينهما؟
-> يوفر Sequelize طريقتين:

أسئلة المقابلة المتقدمة c ++
  • ينتمي إلى
Address.belongsTo(Customer); // Will add a customerId attribute to Address to hold the primary key value for Customer.
  • لديه واحد
Customer.belongsTo(Address); // Will add an attribute customerId to the Address model.

ما هو الفرق بين ينتمي إلى و لديه واحد ؟
-> لديه واحد يُدرج مفتاح الارتباط في النموذج المستهدف بينما ينتمي إلى يدرج مفتاح الاقتران في النموذج المصدر.

يمكننا إنشاء حل عن طريق الجمع بين foreignKey و targetKey مع belongsTo و hasOne العلاقة على النحو التالي رمز:

صافي ماوي مقابل بليزر
Customer = sequelize.define('customer', { uuid: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV1, primaryKey: true }, /* more attributes */ }); Address = sequelize.define('address', { /* attributes */ }); Address.belongsTo(Customers, {foreignKey: 'fk_customerid', targetKey: 'uuid'}); Customers.hasOne(Address, {foreignKey: 'fk_customerid', targetKey: 'uuid'});

مفتاح غريب

  • في ينتمي إلى العلاقة ، سيتم إنشاء المفتاح الخارجي من اسم النموذج الهدف واسم المفتاح الأساسي الهدف. يوفر Sequelize foreignKey خيار تجاوز defaultValue.

مفتاح الهدف

  • المفتاح الهدف هو العمود الموجود في النموذج الهدف الذي يشير إليه عمود المفتاح الخارجي في النموذج المصدر. في ينتمي إلى فيما يتعلق ، بشكل افتراضي ، سيكون المفتاح الهدف هو المفتاح الأساسي للنموذج الهدف. يوفر Sequelize targetKey خيار لتحديد عمود مخصص.

كيفية حفظه ؟

var customer; Customer.create({ firstname: 'Jack', ... }).then(createdCustomer => { // Send created customer to client customer = createdCustomer; return Address.create({ street: 'W NORMA ST', ... }) }).then(address => { customer.setAddress(address) }) };

كيفية إحضار الكيانات ؟ - البرنامج التعليمي: تكملة جمعية مثال واحد لواحد - Nodejs MySQL

-> طريقة الحصول على جميع العملاء بما في ذلك العناوين:

تطبيق "عرض التغريدات المحمية"
Customer.findAll({ attributes: [['uuid', 'customerId'], ['firstname', 'name'], 'age'], include: [{ model: Address, where: { fk_customerid: db.Sequelize.col('customer.uuid') }, attributes: ['street', 'phone'] }] }).then(customers => { console.log(customers); });

مع attributes الخيار ، يمكننا تحديد بعض السمات فقط:

Customer.findAll({ attributes: ['uuid', 'firstname', 'age'] });

و attributes يمكن إعادة تسميتها باستخدام مصفوفة متداخلة:

// 'uuid, firstname' can be renamed to 'customerId, name' as below: Customer.findAll({ attributes: [['uuid', 'customerId'], ['firstname', 'name'], 'age'] });

الممارسة - تكملة مثال واحد لواحد

نقوم بإنشاء مشروع NodeJs / Express على النحو التالي: /nodejs-sequelizejs-one-to-one-mysql /app /config db.config.js env.js /controller customer.controller.js /model customer.model.js /route customer.route.js /node_modules package.json server.js

إنشاء مشروع NodeJs / Express

تثبيت Express و Sequelize و MySQL: $npm install express sequelize mysql2 --save

-> ملف package.json:

{ 'name': 'Sequelize-One-to-One', 'version': '1.0.0', 'description': 'nodejs-express-sequelizejs-One-to-One-mysql', 'main': 'server.js', 'scripts': { 'test': 'echo 'Error: no test specified' && exit 1' }, 'keywords': [ 'NodeJs-Express-SequelizeJs-MySQL' ], 'author': 'loizenai.com', 'license': 'ISC', 'dependencies': { 'express': '^4.16.3', 'mysql2': '^1.5.3', 'sequelize': '^4.37.6' } }

إعداد اتصال Sequelize MySQL - تكملة مثال واحد لواحد

نقوم بإنشاء ملف './app/config/env.js': const env = { database: 'testdb', username: 'root', password: '12345', host: 'localhost', dialect: 'mysql', pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } }; module.exports = env;

- إعداد اتصال Sequelize-MySQL في ملف './app/config/db.config.js':

const env = require('./env.js'); const Sequelize = require('sequelize'); const sequelize = new Sequelize(env.database, env.username, env.password, { host: env.host, dialect: env.dialect, operatorsAliases: false, pool: { max: env.max, min: env.pool.min, acquire: env.pool.acquire, idle: env.pool.idle } }); const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize; db.customers = require('../model/customer.model.js')(sequelize, Sequelize); db.address = require('../model/address.model.js')(sequelize, Sequelize); db.address.belongsTo(db.customers, {foreignKey: 'fk_customerid', targetKey: 'uuid'}); db.customers.hasOne(db.address, {foreignKey: 'fk_customerid', targetKey: 'uuid'}); module.exports = db;

تحديد نماذج التسلسل - تكملة مثال واحد لواحد

- نموذج العنوان: module.exports = (sequelize, Sequelize) => { const Address = sequelize.define('address', { street: { type: Sequelize.STRING }, phone: { type: Sequelize.STRING } }); return Address; }
  • نموذج العميل:
module.exports = (sequelize, Sequelize) => { const Customer = sequelize.define('customer', { uuid: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV1, primaryKey: true }, firstname: { type: Sequelize.STRING }, lastname: { type: Sequelize.STRING }, age: { type: Sequelize.INTEGER } }); return Customer; }

Express RestAPIs - جهاز التوجيه

حدد مسارات العميل في ملف './app/controller/customer.route.js': module.exports = function(app) { const customers = require('../controller/customer.controller.js'); // Create a new Customer app.post('/api/customers', customers.create); // Retrieve all Customer app.get('/api/customers', customers.findAll); }

وحدة تحكم Nodejs Express RestAPI - تكملة مثال واحد لواحد

استخدم وحدة تحكم العميل في ملف './app/controller/customer.controller.js': const db = require('../config/db.config.js'); const Customer = db.customers; const Address = db.address; // Post a Customer exports.create = (req, res) => { // Save to MySQL database var customer; Customer.create({ //customerid: db.sequelize.Utils.generateUUID(), firstname: req.body.firstname, lastname: req.body.lastname, age: req.body.age }).then(createdCustomer => { // Send created customer to client customer = createdCustomer; return Address.create({ street: req.body.street, phone: req.body.phone }) }).then(address => { customer.setAddress(address) res.send('OK'); }) }; // FETCH all Customers include Addresses exports.findAll = (req, res) => { Customer.findAll({ attributes: [['uuid', 'customerId'], ['firstname', 'name'], 'age'], include: [{ model: Address, where: { fk_customerid: db.Sequelize.col('customer.uuid') }, attributes: ['street', 'phone'] }] }).then(customers => { res.send(customers); }); };

Nodejs Express Server.js

في البرنامج التعليمي 'Sequelize One-to-One Example' ، نقوم بإنشاء خادم يستمع عند المنفذ 8080 بالرمز أدناه: var express = require('express'); var app = express(); var bodyParser = require('body-parser'); app.use(bodyParser.json()) const db = require('./app/config/db.config.js'); // force: true will drop the table if it already exists db.sequelize.sync({force: true}).then(() => { console.log('Drop and Resync with { force: true }'); }); require('./app/route/customer.route.js')(app); // Create a Server var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log('App listening at http://%s:%s', host, port) })

اقرأ أكثر

المنشورات ذات الصلة:

تشغيل وفحص النتائج

بدء خادم NodeJs: nodejs-express-sequelizejs-mysql>node server.js App listening at http://:::8081 Executing (default): DROP TABLE IF EXISTS `customers`; Executing (default): DROP TABLE IF EXISTS `customers`; Executing (default): CREATE TABLE IF NOT EXISTS `customers` (`id` INTEGER NOT NULL auto_increment , `firstname` VARCHAR(255), `lastname` VARCHAR(255), `age` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB; Executing (default): SHOW INDEX FROM `customers` Drop and Resync with { force: true }

استخدم ساعي البريد للتحقق من النتيجة ->

- عملاء البريد:

من أين تشتري عملة ogn

[معرف التسمية التوضيحية = attachment_4731 محاذاة = عرض المحاذاة = 577] تكملة واحد إلى واحد رابطة CRUD RestAPI NodeJS Express - طلب آخر [/ caption]

تحقق من قاعدة البيانات بعد إجراء POST:

[معرف التسمية التوضيحية = attachment_4732 محاذاة = عرض المحاذاة = 657] تكملة واحد إلى واحد CRUD RestAPI NodeJS Express MySQL Customer Table [/ caption]

[معرف التسمية التوضيحية = attachment_4733 محاذاة = عرض المحاذاة = 725] تكملة رابطة واحد إلى واحد CRUD RestAPI NodeJS -Express MySQL - جدول العناوين [/ caption]

ص رئيس ()
Executing (default): INSERT INTO `customers` (`uuid`,`firstname`,`lastname`,`age`,`createdAt`,`updatedAt`) VALUES ('9316ba60-4313-11e8-84e8-85431d41448c','Mary','Taylor',37,'2018-04-18 14:19:58','2018-04-18 14:19:58'); Executing (default): INSERT INTO `addresses` (`id`,`phone`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'(251) 546-9442','2018-04-18 14:19:58','2018-04-18 14:19:58'); Executing (default): INSERT INTO `customers` (`uuid`,`firstname`,`lastname`,`age`,`createdAt`,`updatedAt`) VALUES ('53697ff0-4314-11e8-84e8-85431d41448c','Jack','Davis',37,'2018-04-18 14:25:21','2018-04-18 14:25:21'); Executing (default): INSERT INTO `addresses` (`id`,`phone`,`createdAt`,`updatedAt`) VALUES (DEFAULT,'(671) 925-1352','2018-04-18 14:25:21','2018-04-18 14:25:21');
  • البحث عن جميع العملاء:

[عنوان معرف = attachment_4734 محاذاة = عرض محاذاة = 484] تكملة رابطة واحد إلى واحد CRUD RestAPI NodeJS Express MySQL - الحصول على جميع طلبات العملاء [/ caption]

مصدر الرمز

- تكملة- واحد إلى واحد- NodeJS-Express-MySQL

#nodejs #express # Sequelize #association

loizenai.com

تكملة مثال واحد لواحد - جمعية Nodejs - loizenai.com

في البرنامج التعليمي ، أرشد كيفية إنشاء نماذج ارتباط 'Sequelize One-To-One example' باستخدام قاعدة بيانات NodeJS / Express RestAPI و MySQL.

أنظر أيضا: