GORM Many-to-one with mapping table - mysql

I have a couple of mysql tables with many-to-one relationship which is using a mapping table for the relationship. It is as below
book_type_map
Column Datatype
book_id Char(36)
book_type_id Char(36)
book_type
Column Datatype
book_type_id Char(36)
book_type Text
default TinyInt(1)
books
Column Datatype
book_id Char(36)
As you can see, the book table or the book_type table has no columns referring eachother, I need to be able to access book_type from the book. These are my domain objects for Book and BookType
class Book {
String id
BookType bookType
static mapping = {
table 'books'
id column: 'book_id', generator: 'uuid2'
bookType joinTable: [ name: 'book_type_map',
key: 'book_id',
column: 'book_type_id']
}
}
class BookType {
String id
String type
Boolean default
static mapping = {
table 'book_type'
id column: 'book_type_id', generator: 'uuid2'
type column: 'book_type'
}
}
When I run this I get this exception when I do a Book.findAll()
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'this_.book_type_id' in 'field list'
I think my mapping is incorrect. I'd appreciate it if anyone could point me in the right direction.

Having a join table in general only makes sense for one-to-many or many-to-many relationships. In this example, Book can have only one BookType so why does there need to be a join table? You would just have a column with the BookTypeId.
I think what you are looking for is:
class Book {
String id
static hasMany = [bookType: BookType]
static mapping = {
table 'books'
id column: 'book_id', generator: 'uuid2'
bookType joinTable: [ name: 'book_type_map',
key: 'book_id',
column: 'book_type_id']
}
}
See the docs for more details
EDIT
If you are set on this table structure you can flip the relationship (not a fan of this). This structure doesn't really make sense to me, but will work:
class Book {
String id
static mapping = {
table 'books'
id column: 'book_id', generator: 'uuid2'
}
}
class BookType {
String id
String type
Boolean default
static hasMany = [books: Book]
static mapping = {
table 'book_type'
id column: 'book_type_id', generator: 'uuid2'
type column: 'book_type'
books joinTable: [ name: 'book_type_map',
key: 'book_type_id',
column: 'book_id']
}
}

Related

LEFT JOINS and aggregation in a single Prisma query

I have a database with multiple tables that frequently need to be queried with LEFT JOIN so that results contain aggregated data from other tables. Snippet from my Prisma schema:
model posts {
id Int #id #unique #default(autoincrement())
user_id Int
movie_id Int #unique
title String #db.Text
description String? #db.Text
tags Json?
created_at DateTime #default(now()) #db.DateTime(0)
image String? #default("https://picsum.photos/400/600/?blur=10") #db.VarChar(256)
year Int
submitted_by String #db.Text
tmdb_rating Decimal? #default(0.0) #db.Decimal(3, 1)
tmdb_rating_count Int? #default(0)
}
model ratings {
id Int #unique #default(autoincrement()) #db.UnsignedInt
entry_id Int #db.UnsignedInt
user_id Int #db.UnsignedInt
rating Int #default(0) #db.UnsignedTinyInt
created_at DateTime #default(now()) #db.DateTime(0)
updated_at DateTime? #db.DateTime(0)
##id([entry_id, user_id])
}
If I wanted to return the average rating when querying posts, I could use a query like:
SELECT
p.*, ROUND(AVG(rt.rating), 1) AS user_rating
FROM
posts AS p
LEFT JOIN
ratings AS rt ON rt.entry_id = p.id
GROUP BY p.id;
I'm not exactly sure how/whether I can achieve something similar with Prisma, because as it stands right now, it seems like this would require two separate queries, which isn't optimal because there is sometimes the need for 2 or 3 joins or SELECTs from other tables.
How can I make a query/model/something in Prisma to achieve the above?
Yes, this is possible with Prisma!. For making this work, you need to specify on your "schema.prisma" file how are models related with each other. That way, code generation will set the possible queries/operations.
Change it to this:
model Post {
id Int #id #unique #default(autoincrement()) #map("id")
userId Int #map("user_id")
movieId Int #unique #map("movie_id")
title String #map("title") #db.Text
description String? #map("description") #db.Text
tags Json? #map("tags")
createdAt DateTime #default(now()) #map("created_at") #db.DateTime(0)
image String? #default("https://picsum.photos/400/600/?blur=10") #map("image") #db.VarChar(256)
year Int #map("year")
submittedBy String #map("submitted_by") #db.Text
tmdbRating Decimal? #default(0.0) #map("tmdb_rating") #db.Decimal(3, 1)
tmdbRatingCount Int? #default(0) #map("tmdb_rating_count")
ratings Rating[]
##map("posts")
}
model Rating {
id Int #unique #default(autoincrement()) #map("id") #db.UnsignedInt
userId Int #map("user_id") #db.UnsignedInt
rating Int #default(0) #map("rating") #db.UnsignedTinyInt
entryId Int
entry Post #relation(fields: [entryId], references: [id])
createdAt DateTime #default(now()) #map("created_a") #db.DateTime(0)
updatedAt DateTime? #map("updated_a") #db.DateTime(0)
##id([entryId, userId])
##map("ratings")
}
Note: Please follow the naming conventions (singular form, PascalCase). I made those changes for you at the schema above. ##map allows you to set the name you use on your db tables.
Then, after generating the client, you will get access to the relational operations.
// All posts with ratings data
const postsWithRatings = await prisma.post.findMany({
include: {
// Here you can keep including data from other models
ratings: true
},
// you can also "select" specific properties
});
// Calculate on your API
const ratedPosts = postsWithRatings.map( post => {
const ratingsCount = post.ratings.length;
const ratingsTotal = post.ratings.reduce((acc, b) => acc + b.rating, 0)
return {
...post,
userRating: ratingsTotal / ratingsCount
}
})
// OR...
// Get avg from db
const averages = await prisma.rating.groupBy({
by: ["entryId"],
_avg: {
rating: true
},
orderBy: {
entryId: "desc"
}
})
// Get just posts
const posts = await prisma.post.findMany({
orderBy: {
id: "desc"
}
});
// then match the ratings with posts
const mappedRatings = posts.map( (post, idx) => {
return {
...post,
userRating: averages[idx]._avg.rating
}
})
You could also create a class with a method for making this easier.
But I strongly recommend you to implement GraphQL on your API. That way, you can add a virtual field inside your post type. Any time a post is requested alone or in a list, the average will be calculated. In that same way, you would have the flexibility to request data from other models and the "JOINS" will get handled for you automatically.
Last but not least, if you ever want to do a lot of queries at the same time, you can take advantage of the Prisma transactions.

table references a table which in turn references another table

I'm using gorm, and I have this structure where the User table contains a foreign key referencing Address, which then references Country.
type User struct {
ID int `gorm:"column:id; primaryKey; autoIncrement" json:"id"`
Address Address
AddressID int `gorm:"column:address_id;foreignKey:AddressID;references:ID" json:"address"`
}
type Address struct {
ID int `gorm:"column:ID;primaryKey;autoIncrement;" json:"id"`
CountryCode int `gorm:"column:country_code; foreignKey:CountryCode; references:Code" json:"country_code"`
Country Country
}
type Country struct {
Code int `gorm:"column:code; primaryKey; autoIncrement" json:"code"`
Name string `gorm:"column:name" json:"name"`
ContinentName string `gorm:"column:continent_name" json:"continentName"`
}
relationship explained in the photo:
Now when I return a user using:
db.Model(&user).Where().First() // or Find()
I get the Address, and Country Empty, like this:
{
ID: 1,
AddressID: 2,
Address: {
// empty address.
}
}
I did create function repopulating the Address and Country records for me, similar to this:
func PopulateUser(user) User {
addr = FindAddresByID(user.ID)
cntr = FindCountryByCode(addr.Code)
addr.Country = cntr
user.Address = addr
return user
}
but my questions:
is there a function in Gorm which can do that for me without me creating the function?
can Associations help in this case?
if I want the address to be deleted when the user deleted, how I can do this in Gorm?
I tried to find answers on my own, but the documentation is a bit messy.
The documentation shows the foreign key tags to go at the struct reference.
i.e in your case those should be at Address and Country instead of AddressID and CountryCode. Something like:
type User struct {
Address Address `gorm:"foreignKey:AddressID;references:ID"`
AddressID int `gorm:"column:address_id"`
}
type Address struct {
CountryCode int `gorm:"column:country_code"`
Country Country gorm:"foreignKey:CountryCode; references:Code"`
}
Please try with those.
For
Please see eager loading here
db.Preload("User").Preload("Address").Find(&users)
You can use cascade tag on the column.
type User struct {
gorm.Model
Name string
CompanyID int
Company Company `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`
}

How to create entity column with TIME type in TypeORM

How do i create an entity column to store TIME data type from MySQL?
db schema:
CREATE TABLE test (
id INT PRIMARY KEY,
elapsed_time TIME
);
entity:
#Entity()
export class TestEntity {
#PrimaryGeneratedColumn()
id: number;
#Column({name: 'elapsed_time'})
elapsedTime: Date;
}
turns out as easy as this
#Column('time', {name: 'elapsed_time'})
elapsedTime: Date;

Grails - [1:N] Relationship issue

I have 2 different domain classes, one for Employee and one for Departments. The relationship between them is [1:N],which means that many employees can work at one Department but not vice versa. The issue is that, after Grails creates the tables from the domain classes when the project runs, for one employee, the department Id of that table references the id on Department Table. For example, for a user named "Peter", department id would be 1.
The department table also has names for the departments, along with the department id's.
How can I reference the department_id in employee table to point at department.name instead of department.id ?
Department Domain Class :
class Department {
String name
static hasMany = [
employees: Employee
]
static constraints = {
}
static mapping = {
version false
}
def String toString() {
name
}
}
Employee Domain Class :
class Employee {
String firstName
String lastName
String email
String country
int born
static belongsTo = [department: Department]
static constraints = {
firstName(blank: false)
lastName(blank: false)
born(blank: false)
email(blank: false, email: true)
country(blank: false)
}
static mapping = {
version false
}
}
What I need is, when in Employee table, the department_id column to reference at department.name instead of department.id.
I guess you need to configure that the Primary Key of the Department table is 'name' instead of the default 'id' column. Grails will then use the name as the Foreign Key.
i.e.:
class Department {
...
static mapping = {
id name: 'name'
}
...
}
ref (Grails 3.1) : http://docs.grails.org/3.1.x/ref/Database%20Mapping/id.html

Designing JPA Entity for Database Table

I am designing a voting application and designed a database with 2 tables - State and District.
The two tables are -
State details table
State_ID NUMBER(3)
State_name VARCHAR2(30)
PRIMARY KEY(State_ID)
District details table
District_ID NUMBER(3)
State_ID NUMBER(3)
District_name VARCHAR2(30)
PIN_Code NUMBER(6)
PRIMARY KEY(District_ID)
UNIQUE(State_ID, District_name)
FOREIGN KEY(State_ID)
As two states can have a district with same name, I am considering the combination of State ID and District name as UNIQUE by combination.
Now I have to design JPA Entities for these two tables, but I am unable to design because, in the database design, the District table has State ID in it as Foreign Key, but when it comes to designing entities having a State object inside District sounds meaningless, because if I keep HAS-A relationship in my mind, then District doesn't have a State in it. A State HAS-A list of Districts. This is not in accord with the above database design.
Can someone please help me in designing JPA Entities for this. Please suggest if the database design needs modification too.
Thanks.
An example JPA approach based on Rick's proposal:
#Entity
#Table(name = "States")
public class State {
#Id
#Column(nullable = false, columnDefinition = "CHAR(2) CHARACTER SET ascii")
private String code;
#Column(nullable = false, length = 30)
private String name;
#OneToMany(mappedBy = "state")
private Collection<District> districts;
public State() { }
// getters, setters, etc.
}
#Entity
#Table(name = "Districts", uniqueConstraints = {
#UniqueConstraint(columnNames = { "state_code", "name" })
})
public class District {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false, columnDefinition = "SMALLINT UNSIGNED")
private short id;
#Column(name = "state_code", nullable = false,
columnDefinition = "CHAR(2) CHARACTER SET ascii")
private String code;
#Column(length = 30)
private String name;
#ManyToOne
#JoinColumn(name = "state_id")
private State state;
public District() { }
// getters, setters, etc.
}
NOTE: due to usage of columnDefinition attribute the above entities are not portable across databases.
CREATE TABLE States (
code CHAR(2) NOT NULL CHARACTER SET ascii,
name VARCHAR(30) NOT NULL,
PRIMARY KEY(code)
);
CREATE TABLE Districts
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
state_code CHAR(2) NOT NULL CHARACTER SET ascii,
...
PRIMARY KEY(id),
UNIQUE (state_code, name)
);
Notes:
* May as well use the standard state codes (AK, AL, ...) if you are talking about the US.
* Probably the only purpose of States is to spell out the name.
* I was explicit about ascii in case your table defaults to utf8.
* MySQL uses VARCHAR, not VARHAR2.
* You could get rid of Districts.id and have simply PRIMARY KEY(state_code, name), but I am guessing you have a bunch of other tables that need to join to this one, and a 2-byte id would be better than the bulky alternative.