BackboneJS: How to cascade Model#destroy? - javascript

I have a relational DB (MySQL) at the backend and cool BackboneJS at the frontend. I have several tables (models in BackboneJS jargon) that are interconnected through foreign keys.
PROBLEM
How do I destroy a specific model, such that destruction cascades to all child models?
EXAMPLE
Consider this quick schema:
PERSON
id
name
PHONE_NUMBER
id
person_id
number
EMAIL_ADDRESS
id
person_id
email
Consider that we have a person "Jack" stored in DB with some phone numbers and email addresses. Also, we have BackboneJS models/collections defined for all of the 3 tables and data is loaded into them. A user on the frontend decides to delete records of Jack with a click.
Now here are a few approaches to delete all records of Jack:
APPROACH#1
Call "destroy" on all models of PhoneNumbers and EmailAddresses related to Jack, then call "destroy" on Jack itself.
Problem(s)
Too many AJAX calls for one action.
User will have to wait for a lot of time. (More dependants, more time)
Deletion will be non-transactional. If user closes the browser during, data will be corrupted.
APPROACH#2
Define foreign key relationships at database level, that ensure cascade deletion of PHONE_NUMBERs and EMAIL_ADDRESSes when a PERSON row is deleted. Then "destroy" BackboneJS model for Jack at frontend.
BackboneJS Models for dependants will never know what happened to their corresponding records in the backend. So they'll remain intact.
APPROACH#3
Create a URL on server side application "/thoroughly-delete-person" (which makes sure to delete a person with all of its dependants) and invoke it from the frontend instead of calling BackboneJS's Model#destroy on Jack.
Same problem as in Approach#2
So seems like there is no perfect solution for this simple problem. Did you face it too? What approach did you take and why was it better?

I had a similar problem, and I went with approach #2, except with one difference.
If you can, represent Jack as a single Backbone Model that contains phone_number and email_address. You can pass the Jack model to other Backbone Views to share Jack's model data. You can then call destroy on the Jack model.
On the backend I used an on delete cascade, so I could just make a query:
delete from PERSON where id = JACK_ID;
I don't know the syntax for mysql but something like:
PERSON
id
name
PHONE_NUMBER
id references PERSON (id) on delete cascade
person_id
number
EMAIL_ADDRESS
id references PERSON (id) on delete cascade
person_id
email
I'm not sure how well this will fit with your current problem context, but this is similar to what I did, and it works for me.

Related

Is there any way by which we can create relationship in dynmodb

I am new to Amazon Dynamo DB, I have created a user table and address table.and I want to retrieve all users with their particular address as I have assigned user_id in address table to each address. So how can I get user info with address with one query rather than querying both table and merge after. Is their any way like in MySQL we can use JOIN?
Dynamodb is not meant for these types of queries; especially aggregation queries are not ideal. DynamoDB is mainly good for fast lookups for predefined access patterns (e.g. get all items in shopping cart for user ID X).
Since addresses are unique properties of users, you might be able to add an attribute to the user ID table. So basically you have one table with all user data and their properties, including address, that you can query by user ID.
If you need to support different queries I'd suggest you note them all down first before deciding on your data model. (E.g. get all users and sort by last name, get all users living in city X). If the data model in dynamodb is too complex to support all these access patterns you might need to change to a SQL-like db instead.
Edit: note that there are ways to model relationships in dynamodb but they are not trivial. For some examples see the link below. But as suggested above, first define your access patterns before deciding on your data model.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-modeling-nosql-B.html

How to show records *only* from current user php

I'm developing a web app that allows me to generate product orders in PHP. When I first started, I was thinking only about my product orders, however, I have 3 more sales representatives and I would like for them to use it as well.
The problem I'm currently facing is that whenever I'm looking for product orders (using an ajax), all users are allowed to see all the product orders. I would like that each user can only see **their* product orders, but I'm not sure how the query should be.
What would the query be considering these tables?
Thanks in advance!
UPDATE:
So, thanks to #Nicolas answer, I was able to get only information for a selected vendor. However, the 'nombre_cliente(client name)' from 'clientes' tables is wrong for every row. It is showing only the first row. Other information is correct, except for the name. Here is what the results look like now, and how I'm looping through the data.
results
looping
Thanks in advance to everyone.
From what i understand, You would need to know who's asking the server for every request. There's multiple way to achieve this and we don't have enough informations about your infrastructure to give you a good way to accomplish this. Are you using PHP session, are you using an API with API keys, etc. Either way, To get only the product order for a particular vendor, you would need to execute a SQL that would look like that :
SELECT * FROM `facturas` WHERE `id_vendedor` = 1;
In this example, 1 is the id of the connected user.
This request will filter every order and returns only the one that have been done by the user with the id : 1.
You could also join both tables together and filter by some other property of the user table. Lets say we want to get every order by the user whose name contains "john". we would do a request like that :
SELECT facturas.* FROM `facturas` JOIN `users` ON `facturas`.`id_vendedor` = `users`. `user_id` WHERE `users`.`firstname` LIKE '%john%';
In this case, we are joining both table, mapping every id_vendedor to an user_id in the user table, and filtering by firstname. The like operator can be translate to : 'anything john anything'.
IMPORTANT
If you are doing SQL request in any language, make sure you are binding your parameters
Thanks to #Nicolas help, I was able to fix my problem. The final query is:
SELECT * FROM facturas JOIN clientes ON facturas.id_cliente=clientes.id_cliente where facturas.id_vendedor=$current_user (variable that I used to keep track of who is logged in)

Sequelize: Where should these methods reside

You have 2 tables:
Users
Accounts
A user can have many accounts.
You need to add an account to a user. Using Sequelize, you can attach an instance method to the User model called addAccount(). But also, if you look at it from a different angle, the Account table is really creating a new record, so the Account model could have a class method called createAccount().
Which is more semantically correct? Or should the solution be a mix of both where you call addAccount() on a user instance and that method calls the class method createAccount() on the Account model?
And considering that this is a node/express app, the information to create the account needs to be validated and then parsed from the request. Where would you make that validation/parsing happen? In the routes before calling the account creation method? Or as a 'private' function (__parseReq) in the class methods of either the User model or the Account model?
If I were in your position, I would prefer to use addAccount on a user instance. The main reason is because by doing so, you can easily say that the newly created account "belongs to" the user instance in question.
Anyway, if (for some reasons) you really need to create an individual account without the presence of a user instance, you can still use Account.create().
For the value validation, you could either manually validate before doing sequelize operations or you could define your validation rules in the model definition (more info here).

Loopback filter using related model field

Imagine we have two tables, session and movie in postgresql. The table session has a foreignkey to movie. How can i define a relation in movie so that i can ask for movies with filters on session. This table, for example, has a column created and i want to ask for results that has sessions after today with a custom method in Movies.js.
The table session has a foreignkey to movie, then you can define relations on both models(use a custom foreign key if necessary). Then, you can simply query data through the relation you have already defined. just use find, include, scope and where to get the data you want. If you can paste your json files for both models, it will be easy to figure it out.

How can i use REST in python django for multiple tasks

This is the first time i am using REST for any web applications.
For normal get an post and i simply call the API done in Django Rest Framework.
But i am not able to think how can i deal with situations where something more needs to be done.
Suppose I have
List of users in database and their product they have bought.
Now i have web form where if someone adds the user and then submit the button , then
I have to get the list of items bought by that user in 5 hour window
Update the row in database which says buy_succeessful to false
Then again get the list of orders from the items he has bought and then update the rows with order_successful to false
Now current in my submit actions i am doing like
call to api to add the user in override manual enrty table. This is simple post to that table
Then after getting the sucessful tehn i again call api to list of items this user has bought using Query parameters . Then i have the list
Then again i loop through the list and post to api for updating that record in datbase
and so on
I am feeling this is not right.
I have found that quite often there are some more things to do tahn just saving individual objects in database.
whats the best way to do that. DO i need to have view api for every function
Try the 3rd step of the DRF Tutorial:
http://www.django-rest-framework.org/tutorial/3-class-based-views
Here, it shows how to do a "PUT" request for updating data. And also some of the other DRF features.
Also, you can reference serializer.object which is the object instance of the django model record that you are saving to the database. This question here talks about adding extra attributes, etc... before saving to the database:
Editing django-rest-framework serializer object before save
You can also access the record post_save and there are other hooks in the framework that you can use.

Categories

Resources