How to set up intermediary table in MySQL for ManyToMany relations in squeryl for Play 2 framework? - mysql

I'm still learning all the ins and outs of web development, scala, play 2.0, and squeryl and I'm trying to set up a ManyToMany relation between two of my tables.
I've looked over the information found here but I'm having trouble with the intermediary table. I've looked all over and I can't find a good example of how it should be structured.
I'm using MySQL for my database and I've tried using foreign keys and primary keys in the intermediary table, but neither have worked, or maybe I'm just doing it wrong. So, could someone give me a clear example of how the intermediate table should look?
For a little more information, the basic structure of the two tables I want to relate are as follows.
tableOne (
name varchar(255)
);
tableTwo (
name varchar(255),
idCode varchar(255)
);
They will be related by the name in tableOne and the idCode in tableTwo which is just an abbreviated form of tableTwo's name column.
So using MySQL, squeryl, and the format shown in the link, can anyone help me get this going?

To relate the two tables, you will need to establish a ManyToMany relationship in your schema. Assuming you have defined your tables with the names tableOne and tableTwo in your schema, something like this probably what you want:
First create a class that joins the two tables:
class TableOneToTwo(
name:String = "",
idCode:String = "") extends KeyedEntity[CompositeKey2[String, String]] {
def id = compositeKey(name, idCode)
}
Then map the relation in your Schema
val tableOneToTwo = manyToManyRelation(tableOne, tableTwo).via[TableOneToTwo]((t1, t2, jt) => (t1.name === jt.name, t2.idCode === jt.idCode))
Then you would just need to create the corresponding table in your DB - which should have two fields - name, id_code (named according to your naming convention).
If you need a reference, this should point you in the right direction: http://squeryl.org/relations.html

Related

Creating tables for many to many relationship.Will it effect normalization?(Laravel)

My database tables:
1.jobs table having fields id,name
2.locations table having fields id,name
Jobs can have more than one location and locations can have more than one jobs.So i added a table job_locations having id,job_id,location_id.
But my doubt is that if i create a table like this, will it effect normalization ?If i need to connect more tables to locations table then DB will have more tables.
(Example : if users table have more than one location and vice versa, i need to create a table as job_users too..)
I have another solution, that is to add location_id in jobs table. So jobs table fields will look like this: id,name,location_id. Then i will store all location ids as array in location_id as string.(But eloquent method will not work here).
which method is better and why?? OR Is there any other solutions?
No it will not affect normalization.
such bridge tables(weak entities) are used to produce 2NF
See for example https://geekyisawesome.blogspot.com/2011/03/database-normalization-1-2-3-nf.html
A Bridge table must be used for such m:n relationship to conform with normalization, as else you would have multiple identical values in a table.

What's the meaning of foreignKey in Sequelize.hasMany/belongsTo?

I was recently using Sequelize the ORM.
I have two tables. One is Users and the other is Posts
The schema of these two tables are as follows
Users {
id: Integer,
name: String,
age: Integer
}
Posts {
id: Integer, // refers to the id of post itself
author_id: Integer, // refers to the id of the author of this post
title: String,
content: String
}
I want to create an one(Users)-to-many(Posts) association between them. In order to do that, I need to specify the hasMany & belongsTo in the models.
However, I am very confused about the meaning of the parameters foreignKey / sourceKey / targetKey.
Say that I already define and create my table with migrations. The name of the attribute which is the foreignKey is author_id in this case.
My guess is, in belongsTo, foreignKey means "the name of the attribute that is going to be foreignKey in the source table"?
But in hasMany, foreignKey means "the name of the attribute that is referenced by the coming foreignKey"
So, foreignKey in belongsTo will be author_id (in table Posts) but foreignKey in hasMany will be id (in table Users) ?
Furthermore, what on earth do the sourceKey/targetKey mean!?
Well... you have an interesting case above... if you used user_id instead of author_id then you might get away without declaring these as sequelize might assume them correctly... However because you named it author_id then your hasMany definitely needs to know that the foreign key is named author_id in your post table... Let's say that you named your id in the user table something like "user" instead of "id".... well sequelize won't understand that and be able to infer what it is joining on, so you would say the the sourceKey = "user" and foreignKey = "author_id"... To further that one more you may run into issues in database design where you need to specify what the targetKey or otherKey is because someone was naming things whacky... so like you said above in your belongsTo author_id would have no clue that it was supposed to map back to "user" for it's join, so you would specify foreignKey = "author_id" and otherKey = "user"... This stuff took me a while to wrap my head around as well because i did not get to design the database i implements graphql/sequelize against... Therefore i had to make wide use of sourceKey, targetKey, and otherKey etc etc in my joins..
Try and think of it really logically and it will make more sense... if your primary key is always "id" and your foreignKey is always "tablename_id" then you won't need to worry too much about the other properties.. but when naming doesn't line up, sequelize needs to be told what keys to use, and that is why those other properties exist.. Sequelize is damn smart, but it can't make up for poor db design or bad join column naming... Hope this helps, if not i have plenty of examples i can post for you.. Cheers

relationship of mysql in laravel 5.5

I am trying to model with Laravel a database for purchases, in my mysql the relations are [ (for each table in the mysql i have one model)
so I was modeling in Laravel, for the associative table "fornecedor_item_detalhe" I used relation "belongstoMany", it worked out using tinker.
Now comes the problem:
together with the detalhes("fornecedor_detalhe") and the "items" I would like to be able to access the other tables related to "fornecedor_detalhe" which are "fornecedor" and "formpagto"."Has Many Through" will work For this?
And also I would like to link this associative table "fornecedor_detalhes-Item" in relation n: m with another table to create another associative table "fornecedor_detalhe_item_rci".
I've created a model for the pivot table "fornecedor_detalhe_item", but I'm not exactly sure how to do that, as long pivot tables don't have a primary key, how can i reference to them in the other pivot table
I did not codify anything, I'm just trying to model the same thing in laravel.
If you have any suggestions about MER I also accept it.
Thank you
just use Eloquent: Relationships
look in this link realtion types
and you should have model for fornecedor and formpagto
by build relation in model hasMany or belongsTo as your database structure you can call the anywhere just by type relation name
for example
in User Model
public function post()
{
return $this->hasMany(Post::class);
}
when you call in blade $user->post you get all posts related to this user and so on

it is better to make table for each individual column that has options or make options tuples inside model class in django

I am using Django 1.11 and mysql for a web database. I have table for cars ads post. This table has many columns such as title, price, time of the posted ads, and so on, there are many columns for car features like type, condition, cylinders, fuel. Each column of them has many choices. for example, for status there are choices of (excellent, very good, good, poor). For fuel gas, diesel. For cylinder choices are 3,4,5,6,8,12. And so on. I have two options to implement this.
1- The first option is to make table for cars contain columns that does not have options like title. Then connect this table to other tables (table for type, model, fuel, cylinders, and so on). Then connect each table to the main cars table in many to one relationship.
2- The second option is to make tuples inside Django model have these choices and make fields inside the main table instead of making every column individual table and then connect them through foreign key.
My question is that, which option is more effective from the prospective of:
1- Performance and speed
2- Easy to make forms, and to write and save to database the data comes up from the forms.
1- The first option is to make table for cars contain columns that does not have options like title. Then connect this table to other tables (table for type, model, fuel, cylinders, and so on). Then connect each table to the main cars table in many to one relationship.
I'm presuming that you want your models to be like this:
class CarCondition(models.Model):
condition_id = .. # the primary key, preferably an AutoField
condition_name = models.CharField(unique=True)
And then you would populate CarCondition like this:
condition_id | condition_name
1 | 'Excellent'
2 | 'Very good'
etc. And then in Car:
class Car(models.Model):
title = models.CharField()
...
condition = models.ForeignKey('CarCondition', on_delete=...)
...
The ModelForm:
class CarAdForm(forms.ModelForm):
class Meta:
model = Car
And that's it, because all the foreign keys are converted to ModelChoiceFields by Django.
You can save the data like this:
CarAdForm(req.POST).save()
in your view.
2- The second option is to make tuples inside Django model have these choices and make fields inside the main table instead of making every column individual table and then connect them through foreign key.
Since the columns like car_condition will have a tuple of choices, and will be a CharField, you will have to change a few things about the ModelForm, so that it can be rendered as a select widget. Refer as an example this answer. You may or may not require more than CarAdForm(req.POST).save() depending on what you change about the ModelForm.
It seems easier to create and save forms by the first approach. However, in my opinion, ForeignKey is more about referential integrity, whereas you are just trying to limit user input to a few choices, which is better done by the choices tuple.

Insert a new column in SQL

I have a DB consisting of 4 fields.My application will retrieve data from that db. I have one primary key(the id).I also want depending on the id, provide other data that will be organized in a new table. What is better? Create a new table and search again into it, or given the fact that I have already found the row because of the id, create a new element that will be a table. For example can I create a new element named info, and make it be to something like an array,as I want 11 rows,and 2 columns for the info. My SQL code so far is this:
CREATE TABLE people (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
name VARCHAR( 100 ) NOT NULL ,
sex BOOL NOT NULL DEFAULT '1',
birthyear INT NOT NULL
)
What changes do I need to make? This table is already created.
If each row in the existing table now also needs associating with an 11x2 set of data, you're best off creating another table.
Don't try to stuff 22 items of data into a single field, it's a really bad idea.
If, however, it's always the same (22 items), you could just add 22 fields. It depends on how that data is going to be used, searched, joined on, etc.
Exactly how to do that depends on your RDBMS and your interface to it. It may be easier to create a whole new table and copy the old data across. Or the environment you have may allow you to add the columns and it do the leg work for you.
I think it would be best to create a separate new table to contain the additional data. That is primarly because you have more than one record per ID in the original table.
The records in the new table would have a foreign key peopleID field linking them to the people table.
I believe you are hinting at embedding tables. Which isn't really what MySQL is meant to do. Instead, you should do the following; Create a table like that in your example. Then create a new table that will have a column for an ID (which will be the same as that in the people table) and the other various columns. You can then do an inner join to join the two together. Additionally, if you want to reference different tables for different rows, you may want to add in a column for what 'type' it is.
Alternatively, you could use a 'No-SQL' solution like Mongo. This lets you add things dynamically. But I wouldn't suggest doing this until you have a decent grasp of a relational database.