loopback-datasource-juggler/examples/relations.js

93 lines
2.4 KiB
JavaScript
Raw Normal View History

var DataSource = require('../index').DataSource;
var ds = new DataSource('memory');
var Order = ds.createModel('Order', {
2014-01-24 17:09:53 +00:00
customerId: Number,
orderDate: Date
});
var Customer = ds.createModel('Customer', {
2014-01-24 17:09:53 +00:00
name: String
});
Order.belongsTo(Customer);
Customer.create({name: 'John'}, function (err, customer) {
2014-01-24 17:09:53 +00:00
Order.create({customerId: customer.id, orderDate: new Date()}, function (err, order) {
order.customer(console.log);
order.customer(true, console.log);
Customer.create({name: 'Mary'}, function (err, customer2) {
order.customer(customer2);
order.customer(console.log);
});
2014-01-24 17:09:53 +00:00
});
});
Customer.hasMany(Order, {as: 'orders', foreignKey: 'customerId'});
Customer.create({name: 'Ray'}, function (err, customer) {
2014-01-24 17:09:53 +00:00
Order.create({customerId: customer.id, orderDate: new Date()}, function (err, order) {
customer.orders(console.log);
customer.orders.create({orderDate: new Date()}, function (err, order) {
console.log(order);
Customer.include([customer], 'orders', function (err, results) {
console.log('Results: ', results);
});
customer.orders.findById('2', console.log);
customer.orders.destroy('2', console.log);
});
2014-01-24 17:09:53 +00:00
});
});
var Physician = ds.createModel('Physician', {
2014-01-24 17:09:53 +00:00
name: String
});
var Patient = ds.createModel('Patient', {
2014-01-24 17:09:53 +00:00
name: String
});
var Appointment = ds.createModel('Appointment', {
2014-01-24 17:09:53 +00:00
physicianId: Number,
patientId: Number,
appointmentDate: Date
});
Appointment.belongsTo(Patient);
Appointment.belongsTo(Physician);
Physician.hasMany(Patient, {through: Appointment});
Patient.hasMany(Physician, {through: Appointment});
Physician.create({name: 'Smith'}, function (err, physician) {
2014-01-24 17:09:53 +00:00
Patient.create({name: 'Mary'}, function (err, patient) {
Appointment.create({appointmentDate: new Date(), physicianId: physician.id, patientId: patient.id},
function (err, appt) {
physician.patients(console.log);
patient.physicians(console.log);
});
});
});
var Assembly = ds.createModel('Assembly', {
2014-01-24 17:09:53 +00:00
name: String
});
var Part = ds.createModel('Part', {
2014-01-24 17:09:53 +00:00
partNumber: String
});
Assembly.hasAndBelongsToMany(Part);
Part.hasAndBelongsToMany(Assembly);
Assembly.create({name: 'car'}, function (err, assembly) {
2014-01-24 17:09:53 +00:00
Part.create({partNumber: 'engine'}, function (err, part) {
assembly.parts.add(part, function (err) {
assembly.parts(console.log);
});
2014-01-24 17:09:53 +00:00
});
});