Resolving many to many relationship MYSQL database - php

I have 3 tables,
users(id) , userproduct (user_id,product_id) and product (id).
When a user adds a product their user_id and the product_id is saved in USERPRODUCT table.
Now at the same time another user can save a product (kind of like "set as favorite") for this I need to save the user_id of the user who saved it and the product_id of the product. This will create another table (call it favorites) however this table is also a resolve to the many to many relationship between "users" table and "product" table.
the question: is it possible for this, to have 2 tables resolving a many to many relationship or is there any other way to solve my issue.
if it is possible how will one be draw this in the ER diagram

it depends on what you want.
you may use only one table and design your relations with boolean fields
USERS(id)
PRODUCTS(id)
USERPROD(userid, productid, isbought, isfavorite, isowned)
or you may use one many-to-many support table for every relation is up to you
maybe you want another field "owner" in PRODUCTS table to store the user id. this is a one-to-one relation

What you want to do is actually describe the kind of relation between user and product: a favorite, or he 'owns' it.
Just add another field to the userproduct-table defining the relation: favorite or owned

Related

create hasMany or one to many relationship from a pivot table - Laravel

I have 3 Tables:
Companies
Products
Images
Now, Companies and Products are Many to Many relationship.
Meaning, 1 company can have many products and a product can belong to multiple companies. So, I have a pivot table called companies_products with pivot or additional columns such as: price, discount, status, etc...
Note: Products table represents only common-data, that is, it does not have price, status, etc... product is only complete with pivot cols because that is how it makes a product unique to each company.
Everything is fine until here. Now because pivot table represents a unique product cols for each company. I also want to attach product-images table to this pivot table. Which means, my structure would be each pivot row hasMany product_images.
But in Laravel I guess pivot tables does not have a model, it is not encouraged to do so. Then how to achieve has-Many with pivot table?
Or any better solution to structure my tables or data?
In summary,
I have 1 companies table and 1 products table (unique).
companies create final product by adding extra data and images(array). I can handle extra data which goes as a pivot cols but not images (which in this case is array of images. I cant have 1 to many directly at products table level because each company adds a product with extra data to it.
You can define a model for a pivot table. It's covered in the Defining Custom Intermediate Table Models of the docs. To do this, the class of your model should extend:
Illuminate\Database\Eloquent\Relations\Pivot
instead of
Illuminate\Database\Eloquent\Model.

MYSQL one-to-one relationship

I started transforming whole database to a normalised database. But there is one thing which I dont understand about relationships:
Let's say I have 2 tables:
Users
-userID (INT-PK)
-userName (varchar)
_favColor (int)
And:
Colors
-colorID (INT-PK)
-colorName (varchar)
Now obviously I have to create a relationship, the question is:
Should I make relationship between Colors Table and Users Table, or between Users Table and Colors Table?
What I've noticed is that when creating a relationship, the relationship does not appear in both tables, it appears in just one of them, and this makes me confused.
For this example I would recommend a 1:M relationship, going from colours to users.
This is because the users table requires information from the colours table, the reason why you'd have a 1:M relationship is because different users may have the same favourite colour.

Save history products in Laravel

I want to write a method to save the history of changes in the table. I have three tables (products, articles and categories). When a user makes a change, for example in the product name. I want to display a message at the product, example: User Jack change the name of product with "ball" on the "ball2016."
I came up with that I created new pivot table "history_products" wherein the columns will: "user_id", "products_id", "created_at" and "updated_at". This table will be connected with table products. I want to used this trigger. You think it's a good idea or in a Laravel can do it in an easier way??
a good source/library is revisionable, the following:
VentureCraft/revisionable

hasMany vs belongsToMany in laravel 5.x

I'm curious why the Eloquent relationship for hasMany has a different signature than for belongsToMany. Specifically the custom join table name-- for a system where a given Comment belongs to many Roles, and a given Role would have many Comments, I want to store the relationship in a table called my_custom_join_table and have the keys set up as comment_key and role_key.
return $this->belongsToMany('App\Role', 'my_custom_join_table', 'comment_key', 'role_key'); // works
But on the inverse, I can't define that custom table (at least the docs don't mention it):
return $this->hasMany('App\Comment', 'comment_key', 'role_key');
If I have a Role object that hasMany Comments, but I use a non-standard table name to store that relationship, why can I use this non-standard table going one way but not the other?
hasMany is used in a One To Many relationship while belongsToMany refers to a Many To Many relationship. They are both distinct relationship types and each require a different database structure - thus they take different parameters.
The key difference is that in a One To Many relationship, you only need the two database tables that correspond to the related models. This is because the reference to the relation is stored on the owned model's table itself. For instance, you might have a Country model and a City model. A Country has many cities. However, each City only exists in one country. Therefore, you would store that country on the City model itself (as country_id or something like that).
However, a Many To Many relationship requires a third database table, called a pivot table. The pivot table stores references to both the models and you can declare it as a second parameter in the relationship declaration. For example, imagine you have your City model and you also have a Car model. You want a relationship to show the types of cars people drive in each city. Well, in one city people will drive many different types of car. However, if you look at one car type you will also know that it can be driven in many different cities. Therefore it would be impossible to store a city_id or a car_id on either model because each would have more than one. Therefore, you put those references in the pivot table.
As a rule of thumb, if you use a belongsToMany relationship, it can only be paired with another belongsToMany relationship and means that you have a third pivot table. If you use a hasMany relationship, it can only be paired with a belongsTo relationship and no extra database tables are required.
In your example, you just need to make the inverse relation into a belongsToMany and add your custom table again, along with the foreign and local keys (reversing the order from the other model).
Try to understand with text and a figure.
One to One(hasOne) relationship:
A user has(can have) one profile. So, a profile belongs to one user.
One to many(hasMany):
A user has many(can have many) articles. So, many articles belong to one user.
Many to many(BelongsToMany):
A User can belong to many forums. So, a forum belongs to many users.

MYSQL modeling relationships: Design and UPDATE/DELETE

I am trying to understand relationships fully, and have gone through alot of tutorials. Still i linger on a few things (using MySQLWORKBENCH):
1. Every user can upload a product
2. Every product can have multiple categories, bids, ratings, etc
3. Every user can have multiple phonenumbers
(there are more, but this is the basic setup)
Is this correct?:
1 - I used a 1:n relationship, since every user can upload multiple products.
2 and 3. I used n:m relationship, since there can be multiple products with multiple categories, bids, ratings, etc.
DELETE/UPDATE:
I used ON UPDATE CASCADE and ON DELETE CASCADE everywhere where there is a foreign key...that being 'product', 'category_tags_has_products', 'bid_price_has_product', 'phone_has_user'.
I tried to delete a product like this (php): mysql_query("DELETE FROM product WHERE id='$id'");
I get a 1054 error, which is a foreign key error.
What are the best practises here? It is to my understanding that i shouldn't need to do deletions in any other than the parent-table?
Thanx!
You have a lot of identifying relationships, which mean that the foreign key form part of the primary key on the second table. This is not necessary in most instances, and is only really useful in instances such as link tables.
To this end I would change the user->product link to be non-identifying, which will make user_id a Foreign Key instead of being part of the Primary Key. In workbench the shortcut for a 1:n non-identifying relationship is key '2' (where as '4' is identifying). This in turn should remove the user_id fields from the tables which product links onto.
When you delete a product, it should cascade to the 3 link tables that it links to. At present it may be that it is trying to delete from users also depending on how the FK is set up. The following should cascade deletions (assuming a deletion is permanent and you just want to clear out all linked records)
DELETE FROM product -> deletes from any table with product_id in
DELETE FROM user -> deletes from any table with user_id in
The same applies for phone, rating, bid_price, category_tags.
I hope this if of use, if you need any further pointers feel free to shout :)
The relations look correct.
To find out what is wrong with your query check the $id variable.
Or check the whole query and then run it in the console/phpMyAdmin/etc:
$query = "DELETE FROM product WHERE id='$id'";
var_dump($query);
mysql_query($query);
P.S.: and don't forget to escape all data got from the users! Like this:
$id = mysql_real_escape_string($_GET['id']);

Categories