RestFul webService and Database Transactions - php

Lately i'm struggling with Rest architecture :p and i usualy raise a lot of problems with it.
Let's say that i have a resource named "user", and that user can have a list of cars.
Im trying to insert that user and his list of cars in the database at once. I know i have to do this with the POST HTTP verb. But how would i achieve this? Should i send only one URL with the user identification and the list of cars somehow encoded or should i use the "user" resource to insert the user, and then for each car, call a POST URL in a resource named "car"?
The second approach has a problem. This process must be implemented with a Database Transaction. If something goes wrong when inserting a car, i want the user to not be regitered in the database.
I know restFul architectures must be stateless, so how can i implement such a transaction using the database functionalities? I know i can implement myself some kind of transaction, but i wanted it to be more automaticaly.
Thanks in advance.

There are a number of ways you can do it depending on the languages you're using in the front and backend and how you plan to send this data. I would solve the problem like so, assuming you're using PHP and MySQL:
Get the data ready, so something like user=123&cars[]=1&cars[]=2&cars[]=3 (I'm using the var cars[] as this will send an array to PHP and you can achieve this by naming your input fields as cars[])
Post this to your backend
Your backend will then process the user and add them to the database if they're not there.
I would then have a table that illustrated the relationship between the user and the cars, something along the lines of:
CREATE TABLE box_to_category (
user_id int(11) NOT NULL,
car_id int(11) NOT NULL
);
In this table I'd clear all cars associated with that user and then add the new cars as POSTed to the backend (the user_id will be associated to a user in a users table and the car_id will be associated to a car in the cars table)
It's a simple set up.

Related

Database set up for multi-way relationships and form data collecting

I've posted a few questions on here and have gotten very great help and support. I'm still fairly new to programming and I'm putting together what I thought would be a simple website for the company I work at. I apologize in advance for my lengthy post/question, I just want to be thorough and clear in what I'm asking. My question is more of needing some help getting pointed in the right direction of how to get started and some best practices to be aware of. What I'm working on right now is to create a system where a user can submit a questionnaire/online form to inquire about a specific product (in this case it's a hard money loan product). The way I am planning on setting it up is to have a database with multiple tables (users, user_info, loan_app, property) and connect these together by referencing each other. I've read about table joins and I understand them conceptually but I have no idea how to implement in practice. I've had a hard time finding actual examples.
Specifically, this is what I am doing and how I am thinking it should work (correct me if I'm wrong or if there's a better way to do it):
1- the user (aka the borrower) signs in to the website. The user log in system references the user table where things like first name, last name, user name, password and user ID are stored. I have included an "active" column in this table so that when a user logs in the condition for them to get into the website is that the username and password match AND the user is activated. This way we can control on the back end certain user accounts access. I have this part working.
2- when the user registers, they only fill out the information that creates a new record in the "user" table. I have created a second table called "user_info" that will contain other data like home address, phone number email etc. But I need to be able to associate the correct record with right user. This is my first issue to wrap my head around. My thinking behind doing this instead of simply putting all this information in the user table is that for one, I might keep adding to that table and make it very big, and two for security reasons, I would like to keep the information separate. I don't know if this thought process has any merit to it though. Again, that's why I'm posting this here.
3- The user, once logged in, clicks on a button on their home screen/dashboard that will take them to the loan "pre-approval application" form, which is the questionnaire. On this form their basic information will be echoed/posted from the "user_info" table to pre-populate certain fields like first name, last name, email, phone number, address etc. So going back to #2 making sure I can associate the user with the correct record in the "user_info" table is critical. THEN, there are additional fields that the user has to fill out in order to submit the application/questionnaire. These form fields will create a new record in the "loan_app" table. This table will have a loanid column that is the primary key for that table, and an auto generated/randomized 6 or 7 digit loan number (loannum). The loanid will be a hidden value but the loan number will be like a reference number that is associated with the loan for the life of it and used for later accounting and recording purposes internally, whether or not it actually becomes a loan. The loanid, I'm assuming here, is the Foreign key in the "user" table and the userid is the Foreign key in the "loan_app" and "user_info" tables correct? If so, how do I incorporate being able to simultaneously associate all these records when the loan application/questionnaire is submitted? My thought would be write individual php scripts that does each of these things separately then have a "master" php that includes all of those individual ones that is placed as the form action associated with the submit button on the form.
Thanks for taking the time to read through this. I'd really appreciate any advice or reference material that I can read up on to learn more about this stuff. My job has a pretty crazy schedule and I travel a lot so I don't have the time to take actual classes to learn this stuff formally. I'm pretty much doing this as I go.
Also, I'm using MAMP with mysql, not sure if that helps any or not...
The user table's primary key userid can be the primary key of the user_info table as well, since each user will have only one user_info record, right? A foreign key constraint is good to ensure only valid userids get recorded in user_info.
The loan_app table can contain a denormalized relationship from loanid to userid so that each loan application is associated with a user. Again, use an FK constraint for integrity.
Don't include loanid in the user table - that would mean each user has a relationship to a single loan application. You already have the one-to-many relationship you need in the loan_app table.

How do you setup relationships with many foreign keys from the same table in PHP ActiveRecord?

I am building a real estate related website that real estate agents and investors can use to track properties submitted in the system and keep track of who is owed what profits. I have the following tables that I am having trouble figuring out how to setup the relationships for in my models using PHP ActiveRecord:
properties
id
primary_profit_sharing
secondary_profit_sharing
commission
referral_payment
users
id
name
email
payments
id
type (commission, referral_payment, etc.)
property_id
user_id
What is the proper way to setup these relationships using PHP ActiveRecord? I would like to be able to access the user information for each payment by something like $property->commission and $property->referral_payment but I can't figure out how to setup the relationships in the models to allow that.
I currently have payments belonging to users and properties, and users/payments have many payments. All the information I was is returned in the query, but not in an accessible ways. I have $property->users but no way of getting the user information for a particular payment type.
The only way I can think of to accomplish what I'm looking for is to setup a table for each payment type, but that doesn't seem like the best way to do it.
In the payments table, instead of using property_id and user_id, maybe you should use fk_object as the foreign key and do your joins using that field. fk_object represents the id of the user or the id of the property.

Reference tables dynamically in MySQL / Codeigniter?

Here is the usecase my team is stuck with:
There are different types of objects in the system, (ex: user, photo, link, video, tag, phototag, etc). Now each object has its own table. When looking up objects for any purpose (say live feed, activity tracking, tagging different object types, etc) ideally the system needs to know three things:
1) The object ID
2) The object type
3) Object details from the object's depending on the usecase
For 1 & 2, i am handling it by adding two columns: object_id, object_type - this will always tell me the ID and what object the Id is referring to. But for step 3 the problem is to get object details I need to know which tables each object relates to. So how do i do that? I am using MySQL and codeignitor php.
One way i can think of is to have a table that has a relation between object and the schema tables. But the downside is then i have to always join this to get the table name then lookup that table. I am hoping to skip any join. Is there anything that can be done within codeignitor for this or any application logic to add which can detect which table to reference based on object type dynamically? And maybe i dont even need the object_Type column and the system can find the table on its own just from the object_id and the page_id or something else?
You are talking about [polymorphic associations][1] which Rails currently supports. I don't think Codeigniter supports this by default (use another layer[ORM]). However, the only thing I can think of is having a library handle this but this will all be conditional statements (ifs).

Optimal MySQL design for user-specific activity feeds

I'm building a website that constructs both site-wide and user-specific activity feeds. I hope that you can see the structure below and share you insight as to whether my solution is doing the job. This is complicated by the fact that I have multiple types of users that right now are not stored in one master table. This is because the types of users are quite different and constructing multiple different tables for user meta-data would I think be too much trouble. In addition, there are multiple types of content that can be acted upon, and multiple types of activity (following, submitting, commenting, etc.).
Constructing a site-wide activity feed is simple because everything is logged to the main feed table and I just build out a list. I have a master feed table in MySQL that simple logs:
type of activity;
type of target entity;
id of target entity;
type of source entity (i.e., user or organization);
id of source entity.
(This is just a big reference table that points the script generating the feed to the appropriate table(s) for each feed entry).
In generating the user-specific feed, I'm trying to figure out some way to join the relationship table with the feed table, and using that to parse results. I have a relationships table, comprised of 'following' relationships, that is similar to the feed table. It is simpler though b/c only one type of user is allowed to follow other content types/users.
user/source id;
type of target entity;
id of target entity.
Columns 2 & 3 in the feed and follow table are the same, and I have been trying to use various JOIN methodologies to match them up, and then limit them by any relationships in the follow table that the user has. This is has not been very successful.
The basic query I am using is:
SELECT *
FROM (`feed` as fe) LEFT OUTER JOIN `follow` as fo
ON `fe`.`feed_target_type` = `fo`.`follow_e_type`
AND fo.follow_e_id = fe.feed_target_id
WHERE `fo`.`follow_u_id` = 1 OR fe.feed_e_id = 1
AND fe.feed_e_type = 'user'
ORDER BY `fe`.`feed_timestamp` desc LIMIT 10
This query also attempts to grab any content that the user has created (which data is logged in the feed table) that the user is, in effect, following by default.
This query seems to work, but it took me sometime to get to it and am pretty sure I'm missing a more elegant solution. Any ideas?
The first site I made with an activity feed had a notifications table where activities were logged, and then friends actions were pulled from that. However a few months down the line this hit millions of records.
The solution I am programming now pulls latest "friends" activities from separate tables and then orders by date. The query is at home, can post the example later if interested?

How to make cakePHP retrieve the data represented by a foreign key?

I have a simple database with multiple tables. I can't figure out how to make cakePHP display the values associated with a foreign key in an index view. Or create a view where the fields of my choice (the ones that make sense to users like location name - not location_id can be updated or viewed on a single page).
I have created an example at http://lovecats.cakeapp.com that illustrate the question. If you look at the page and click the "list cats", you will notice that it shows the location_id field from the locations table. You will also notice that when you click "add cats", you must choose a location_id from the locations table. This is the automagic way that cakePHP builds the app. I want this to be the field location_name.
The database is setup so that the table cats has a foreign key called location_id that has a relationship to a table called locations.
This is my problem: I want these pages to display the location_name instead of the location_id. If you want to login to the application, you can go to http://cakeapp.com/sqldesigners/sql/lovecats and the password 'password' to look at the db relationships, etc.
How do I have a page that shows the fields that I want? And is it possible to create a page that updates fields from all of the tables at once?
This is the slice of cake that I have been trying to figure out and this would REALLY get me over a hump. You can download the app and sql from the above url.
Hah, you figured it out correctly! Cake uses the $displayField variable do decide what to..well, display.
If I remember correctly, by default, cake looks for 'title' and 'name' fields, and if those two are not available, it will simply show your primary key field. Luckily, you can override it the way you figured out yourself ;)
I guess you need to echo $cat['Location']['location_name'] in your view.

Categories