How to query a parent table and inherited child table together in one query - postgresql

I am using go and pq to interface with my postgres database.
I have a simple user table which has basic fields. Id, name, type. My auxillary table, admin inherits from user and adds it's own field panel, and another one that is owner and adds owner. Whether that be using table inheritance, or a supporting table.
My question is if I hit and endpoint that points to user/1 at this point I don't know what type of user this person is yet here. I know we can use jwts and other ways to provide this from the front end. I'm more curious about if there is a way to figure out the user and it's type and query the additional fields in one query?
Ie. I hit the endpoint I would Select from users, get the type, then use that type to get the additional fields. So I would effectively be doing two queries on two tables to get the complete data. Is there a better solution of doing this? Is there some optimizations I could do.

Related

Nest TypeORM Postgres update user's column('number of posts') based on the userId in the Posts Table

I'm wondering if it's possible to auto update the User's column('number of posts') if the Posts table updates. The Post entity has a ManyToOne relation with User('userId'). Is there a way to make the User Table "listen" to the Post Table and automatically updates the number of post column, or i need to write it in the post service create function to do so. I'm new to sql so i'm just trying new stuff. I'm using NestJS,typeORM, Postgres and Graphql
#Kendle's answer does work and has the advantage of pushing the computation and complexity down onto your DB server. Alternatively, you can keep that logic in the application by leveraging TypeORM's Subscribers functionality. Documentation can be found here.
In your specific use case, you could register a subscriber for your Post entity implementing afterInsert and afterRemove (or afterSoftRemove if you soft delete posts) to increment and the decrement the counter respectively.
You don't want to duplicate that data. That's the whole idea of a relational database that different data is kept in different tables.
You can create a view if you want to avoid typing a query with a JOIN each time.
For example you might create the view below:
CREATE VIEW userPosts AS
SELECT
user.id,
user.name,
COUNT(posts.id)
FROM users
LEFT JOIN posts ON user.id = posts.user_id
ORDER BY user.id;
Once you have created the view your can query it as if it were a table.
SELECT * FROM userDate WHERE id = '0001';
Of course I don't have your table definitions and data so you will need to adapt this code to your tables.

Inheriting Parent Table with identifier (Postgres)

Sorry if this is a relatively easy problem to solve; I read the docs on inheritance and I'm still confused on how I would do this.
Let's say I have the parent table being car_model, which has the name of the car and some of it's features as the columns (e.g. car_name, car_description, car_year, etc). Basically a list of cars.
I have the child table being car_user, which has the column user_id.
Basically, I want to link a car to the car_user, so when I call
SELECT car_name FROM car_user WHERE user_id = "name", I could retrieve the car_name. I would need a linking component that links car_user to the car.
How would I do this?
I was thinking of doing something like having car_name column in car_user, so when I create a new data row in car_user, it could link the 2 together.
What's the best way to solve this problem?
Inheritance is something completely different. You should read about foreign keys and joins.
If one user drives only one car, but many users can drive same car, you need to build one-to-many -relation. Add car_name to your user table and JOIN using that field.

Symfony2: Collection of dropdown select lists for a many-to-many relationship

The objective:
Having a many-to-many relation be displayed as a dynamic list of select inputs(single choice dropdown list)
User arrives on page with a single select field (multiple = false) populated with persisted entities and add/remove buttons. By clicking the add button, a new select field with the same options appears below the first, which adds a new entry in the M2M relation. By clicking remove the field disappears and the entry should be removed.
The model:
Two entities: User & Manager. A User has exactly one "special" Manager and unlimited normal Managers.
Managers manage unlimited users.To model this I have created two relationships for which the user is the "owner" (not sure how to translate this)
ManyToOne specialManager
ManyToMany normalManagers
I haven't created a many to many relationship with attribute "special" because the requirement is exactly one special manager and I wasn't sure if Symfony/Doctrine would cause problems down the line.
What I have:
I can display a multiple select field with the existing entities using Entity field type, as per the documentation. Functionally this is what I need, visually it is not.
I can also use the Collection field type to display a single text field, and add or remove more with JS, as per the documentation. Visually this is what I need, but The text fields (entity attribute) need to be replaced by choice field.
The question:
Before I continue digging, is there a simple way to achieve this list of select tags?
For anyone else who may eventually need a dynamic list of select fields:
I initially solved this issue by detaching the field(s) in event listeners, and handling the display/submission manually in the controller.
However I wasn't satisfied with this clunky solution and when I encountered the same need I used a second solution: creating an intermediary entity xxxChoice (in this case ManagerChoice) which is Mto1 inversed related to User and Mto1 related to Manager. Then by creating a ManagerChoiceType form with "Manager" entity field type I was able to easily display my collection of dropdown select lists.

Where to place auditing fields?

In our shop, when we design a database, we typically include auditing attributes for each table (LastUpdateUser, LastUpdateDate, etc). This is common practice, however, I've noticed this becoming an increasing problem when you have tables that "inherit" from other tables, especially using tools such as the entity framework.
For example, if you have tables Customers and Employees, and those tables have a foreign key to table People, then in your entity / class model when you establish the inheritance, you need to change the names for the audit fields because they exist in both tables. Perhaps they need to become PersonLastUpdatedUser and PersonLastUpdatedDate, while the ones from Employees remain as simply LastUpdatedUser and LastUpdatedDate.
When designing tables for inheritance, do you put such audit fields in both tables, or do you just have them in the parent table and update the parent table whenever an attribute changes in a child table?
If you want to use inheritance than those attributes belong to parent table because the parent with related table forms single entity and you track auditing for whole entity. If you for any reason needs those attributes in both tables it should be the first warning that those tables are not good candidates for inheritance.
If you want true auditing, you create separate audit tables that are populated by triggers (never ever by the application or you will miss items that need to be audited).
and they shouw both the old and new value as well as the date and the user or application that made the change.
If you want a last updatedcolumn in each table (which I think is better than having it only in the parenta as that doesn't tell you anything about which of the tables changes last) and you want o use inheritance then you might need to create unique names by adding the table name to lastUpdated. So PersonLastUpdated and OrderLastUpdated, etc.
Or you don't use inheritance.

Entity framework linq to entities

Previously when I wanted obtain related data in an sql query I would join tables, however now in linq to entities I want to get data from a table that is related to the table through another table. I don't know how to perform this sort of query in linq to entities. If someone could help that would be good.
The example is a table named person which has a relationship to table users which is related to table roles. I want to be able to obtain a person that has a particular role. Since person is only related to user and indirectly through user to role, I'm not sure of the query. Also using navigation properties doesn't get me all the way there either.
Any information would be good. Here is an example of the database structure:
db structure http://img194.imageshack.us/img194/4540/persons.jpg
If you using the generator in VS (ie, drap drop the data table and diagram and keys are all set in db), then the thing you are asking could be already there automatically.
e.g.
from Person in Context.Persons
where Person.Name == "PETER PAN"
select Person.User.Role.RoleName;
Exact name need to refer to the code generator, but this is the idea. Linq to entities will help to map foreign keys and those for you.
Edit
Actually I haven't tried using include. But according to msdn:include method, the include should show the object hierarchy to work. So, for your query to work, try:
from c in db.Persons.Include("aspnet_Users").Include("aspnet_Roles")
where c.aspnet_Users.aspnet_Roles.RoleName == "Role" select c
And moreover, will you consider start from roles?
from r in db.aspnet_Roles
where r.RoleName == "ROLE"
select r.aspnet_Users.Persons
(from u in db.aspnet_Users.Include("Person")
from c in db.aspnet_Roles
where c.RoleName == "role"
select u.Persons);
Worked it out thanks for trying though.