Many-to-many relationship in postgres - node.js

In a scenario where we have a many-to-many relationship, what would be the ideal thing to implement an endpoint where you can get the data registered specifically for user X? For example, a class having multiple teachers and a teacher having multiple classes.
I'm using typeorm to make the relations. But on the front end, I have a screen that I need to get all the classes.
That's why I thought of putting the array of classes in the teachers table, because if I implement only the endpoint to get all the classes, I will actually get all the classes, instead of just the classes registered for the user. Or do relationships already solve this problem?
In addition to the specific classes for each teacher, I need to get some data that is in the class. Like name, number of students, etc.

It's quite simple, the best solution would be to put an array of classes in your teacher table. Then they could consume this endpoint to consume the class data.

You need a intermediated table, witch will have the Id of the Teacher (Primary Key of the Teachers table) and the Id of the Class (Primary Key of the Class table).
This way you can know witch or how many class the teacher (ID) have and the same for direction, how many teachers have the class (ID) by query to this table
Example:
Table Teacher:
Id
Name
1
Mary
Table Class
Id
Name
1
Math
2
Geo
Table TeachersClass
Id
TeacherId
ClassId
1
1
1
1
1
2
To know the teacher Mary class:
$ Select * From TeachersClass Where TeacherId = 1
And at the end, with the Class Id you get all information you need from the class table.

Related

Is Django many to many really necessary?

I have been learning to use Django over the last year and Python is not my native programming language. Normally, when I want to create a many to many relationship, I would create 3 tables, one of which contained two foreign keys to each of the other two tables. For this reason, I find the Django manytomany field very unnatural. Does this many to many field create a third table in the database to store the relationship ? If this is the case, then using a many to many field will stop the class structure from directly representing the table structure.
What I am wondering is if there is a reason I should be using this manytomany field or could I get away with using 3 classes to represent a many to many relationship ?
Thanks
Mark
I would create 3 tables, one of which contained two foreign keys to each of the other two tables. For this reason, I find the Django manytomany field very unnatural.
This is exactly what Django is doing behind the curtains. If you inspect the database, you will see a junction table [wiki]. Django simply does this in the background. It simply presents it to the foreground as a field. As you can see in the database Representation of the ManyToManyField:
Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship. By default, this table name is generated using the name of the many-to-many field and the name of the table for the model that contains it. Since some databases don’t support table names above a certain length, these table names will be automatically truncated and a uniqueness hash will be used, e.g. author_books_9cdf. You can manually provide the name of the join table using the db_table option.
You can even add extra fields to this junction table, by defining the model in between explicitly, and specify this in the through=… parameter [Django-doc]. For example:
class Category(models.Model):
name = models.CharField(
max_length=128,
unique=True
)
class Item(models.Model):
name = models.CharField(
max_length=128,
unique=True
)
categories = models.ManyToManyField(
Category,
through='ItemCategory'
related_name='items'
)
class ItemCategory(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
validated = models.BooleanField(default=False)
A ManyToManyField is thus more a concept to make representing and querying more convenient.

I don't understand association class - UML class diagram

I don't yet completely seem to understand how association class works, why the role class attributes can't just be inside the person class?
as example:
Person
name
position
description
Suppose we live in a world where a person must have a role in a company in order to live and a company may exist without persons at all.
If that is all you want to know about the relationship between persons and companies, i.e. only the fact that there are such relationships and nothing more, you model it like this:
Then if you want in addition to capture position and description of the Person's role you use so called AssociationClass (Role in our case):
Each instance of Role has four properties (both an attribute and an end of an association are Properties in UML):
Company
Person
position
description
For example, suppose a person named Scott Tiger has roles in two companies - Food Inc and Water Ltd and each company knows that Scott Tiger has role in it. Then there will be two instances of Role (shown as tuples):
(Food Inc., Scott Tigger, eater, eats here)
(Water Inc., Scott Tigger, drinker, drinks here)
Now, returning to you question, it should be clear that an instance of Person with name, position, description attributes actually "lacks" Company and if you "add" an Company you will get Role, not Person!
So what you proposed in the end of your question is a valid design, if you model Company and Role and a person is just an attribute of Role:
It reads as follows: each instance of Company has zero or more Roles and each instance of Role has only one Company. Both ends of the association are navigable, i.e. Role knows its Company and Company knows its Roles.
UML Specification in clause 9.5.3 gives you the following advice:
A Property may represent an attribute of a Classifier, a memberEnd of an Association, or in some cases both simultaneously.
A useful convention for general modeling scenarios is that a Property whose type is a kind of Class is an Association
end, while a property whose type is a kind of DataType is not. This convention is not enforced by UML.
why the role class attributes can't just be inside the person class?
notice the multiplicity 1..*, if you move position and description into Person you have to manage a collection of them and to associate each to the corresponding Company.
[from your remark]
For a given Person the position and description depends on each associated Compagny, so it is not possible to have the fields you propose except if position and description are both a collection, and to have a way/rule to know which entry in position and description correspond to the right Compagny.
Moving also these information in Person you remove the symmetry, it is also possible to move these information in Compagny, with the same remarks as for Person
An association class is both a class and a relation, when you implement it in a language like C++ or Java etc of course that concept does not exist, so one way is as you propose to move the fields in one of the two classes, or to create a third class having the expected fields more one to a Person and one to Company.
The advantage of the third class is to have all the associated information grouped having the equivalent of :
As example an object diagram can be :
Without the third class you need to know how to associate all the separated information, for instance having all in Person using three vectors to memorize the company and position and description you may use the same index value for all, but this is less clear and when you add/remove a Company for a Person you have to update all these vectors.

How to express counter type entity with UML?

I would need some help with a problem we're facing in a company, trying to model every process and entity.
So far we have used an enhanced conceptual model with entities and attributes with relationships but there are some objects that don't exactly match a dimension or a fact table, and this is an entity that can be called "Shops with sales over X units". There is the entity "sales" and "shop" obviously, that would have it's representation in UML as independent entities and represent at the lower level, each sale and shop.
What we need to indicate in UML is an entity that stores the counter of shops with sales over X units, so this has some kind of behavior or conditions.
If we consider the entity, it would need date-from and date-to, and the value (counter), and creating a connection with the shop entity seems enough, but we miss the behavior that expresses "more than x sales". So the behavior could be for example: Go to the shop entity, take the 1st element and navigate to the sales entity, calculating the sales. If it's over X, then value+1, and so on.
I made a simple version of the problem. Blue boxes represent the entities already created, and the orange one is the counter that should count the shops with some constraints.
Is there any way of using some kind of UML diagram that can help us to solve this problem?
You could realize that with an association class:
ShopSales relates Shop and Sales so you can store the number of sales along with other things you might need in that conjunction. The ShopSalesStats could give you the shops by number of sales.
Another (of many) way(s) would be to just hold the count as public property of Shop and let ShopSalesStates handle the counts on all associated Shops.

Custom Class Object as an Attribute in Core Data? - Swift [duplicate]

I have 2 entities.
entity 1 - People
entity 2 - books
People entity has a property which is an array of string names of their favorite books.
I need to create a relationship that somehow maps the favorite book of a person to the corresponding book entity object(s).
I am not sure how to do this.
So far I have started by creating a relationship in core data model for people by setting destination to "books" and then for the books entity creating a relationship by setting destination to "people".
I don't see or understand how this will automatically pick out each of the person's favorite books...at the end of the day they are both seperate objects. How will the people class know that for a specific people instance that this, this and this book are that person's favorite?
Person attribute as array of string names of books -- very bad idea!
You need a to-many relationship with the Book entity. That's it.
Person <------------>> Book
Then, to get an array of book titles for a particular person:
(person.books as! Set<Book>).map { $0.title }
The person can have an additional to-one relationship (e.g. called favoriteBook) to one of the books.

EF Code First Many to Many Relation Without an Entity

I have read many about how to configure many to many realtionships with EF Code First and fluent configuration. But I couldn't understand why I should create an extra entity for the junction table. Lets assume that I have the following entities:
Department
----------
Id
Name
Material
----------
Id
Name
Now I want to keep records of materials for each department. So I need
DepartmentMaterial
-------------------
DepartmentId
MaterialId
Quantity
What I have read so far I need 3 entities: Department, Material and DepartmentMaterial. So actually I am mapping each table to a corresponding entity which was not I intended to do when I started to learn about DDD. I assumed that EF is going to map that junction table automatically and also queries about material quantities can be done over Department.
Hence, is it possible in EF Code First to configure fluently such a relation without an extra entity?
The junction table can stay out of the conceptual model (class model) if it's only got two foreign keys (DepartmentId, MaterialId). You want to record some data about the association. That's OK, the quantity belongs there. A department has quantity x of material y. Saying that a department has a quantity is meaningless.
This is not against DDD principles. The association class is a first-class citizen in the class model. It could even have its own behavior (like limiting quantities for certain department/material combinations).
This means that your model will not contain a many-to-many association but Department 1-n DepartmentMaterial n-1 Material. And you'll have to query materials of departments through the junction table. This is a very common situation. I hardly ever see pure junction tables in real life. They're collector's items.
Example query:
var query = from d in db.Departments
from dm in d.DepartmentMaterials
select new { Department = d, Materials = dm.Select(x => x.Material)};

Resources