My GORM Primary ID is getting set to an 18 digit number, how can i force this number to start at 1 - go-gorm

I'm using GORM to handle my database operations. My struct is as follows
type Job struct {
gorm.Model
JobID int `gorm:"primary_key"`
Jobitem []Jobitem
SubID int `sql:"not null"`
StartDateTime string `sql:"not null"`
JobStatus string `sql:"not null"`
}
When I insert into the table using this struct, my primary key is 18 digits long, for example: 399758776912773121
Is it possible to get this id to begin at 1 and increment from there?

You're using both gorm.Model and defining your own primary key. So my guess is that gorm automatically thinks you're trying to use Composite Primary Key, since your struct actually looks like this:
type Job struct {
// gorm.Model ↓
ID uint `gorm:"primary_key"` // Gorm uses this
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index"`
// gorm.Model ↑
JobID int `gorm:"primary_key"` // And also detects this
Jobitem []Jobitem
SubID int `sql:"not null"`
StartDateTime string `sql:"not null"`
JobStatus string `sql:"not null"`
}
Long story short, have a look there for some documentation on gorm.Model

Thanks Depado,
It looks like this is built in behavior by the database and not specifically related to GORM. The ID fields are generated using the unique_rowid() function in cockroachdb which is generated by a combination of the timestamp and id of the node executing the insert.

Related

Prisma ORM optional relations for user models

I am using Prisma ORM with PostgreSQL backend for my database, I have users as students and admins and they have slightly different fields so I created a base model User for common info as well as two more models Admin and Student for further unique info but I can't create an admin (a user referencing an admin) without also referencing it to a student, can anybody help with schema structure?
// schema.prisma
enum Role {
SUPERADMIN
ADMIN
STUDENT
}
model User {
id Int #id #default(autoincrement())
citizenId String #unique
hash String
role Role #default(STUDENT)
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
student Student? #relation(fields: [citizenId], references: [citizenId], map: "user_student_fk")
admin Admin? #relation(fields: [citizenId], references: [citizenId], map: "user_admin_fk")
}
model Admin {
id Int #id #default(autoincrement())
citizenId String #unique
name String
schoolId Int
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
user User?
school School #relation(fields: [schoolId], references: [id])
}
model Student {
id Int #id #default(autoincrement())
citizenId String #unique
name String
classId Int
createdAt DateTime #default(now())
updatedAt DateTime #updatedAt
user User?
class Class #relation(fields: [classId], references: [id])
results TestResult[]
}
// ...

Prisma throwing error: Ambiguous relation detected

I'm using prisma and trying to model a referral table for my Postgres database. Not sure if the db schema is correct, but I have a table with a referId, userId: 1 to 1, and referredUserId: 1 to many.
model Referral {
id Int #id #default(autoincrement())
createdAt DateTime #default(now())
updatedAt DateTime #default(now())
referId String // Auto Generate Random String
userId Int #unique
user User #relation(fields: [userId], references: [id])
referredUsersId Int[]
referredUsers User[] #relation(fields: [referredUsersId], references: [id])
}
I'm not sure exactly how to reference these in the User model. I tried
Referral Referral?
UsersReferred Referral[]
But I get an error
Error validating model "User": Ambiguous relation detected
What's the correct way to model a referral table and how can I do it in prisma?
There are multiple relations between the same two models so you would need to specify the name for the relations.
model User {
id String #id
Referral Referral? #relation("UserReferral")
UsersReferred Referral[] #relation("ReferredUsers")
}
model Referral {
id Int #id #default(autoincrement())
createdAt DateTime #default(now())
updatedAt DateTime #default(now())
referId String
userId String #unique
user User #relation(fields: [userId], references: [id], name: "UserReferral")
referredUsersId String
referredUsers User #relation(fields: [referredUsersId], references: [id], name: "ReferredUsers")
}
Here's the reference for Disambiguating relations: Reference

Laravel Query Builder pivot table connection

I'm trying to get the all related countries which the country is belongs to the regions it is many to many relation.
I want it in the query builder realations
this I pivot table
id bigint unsigned auto_increment
primary key,
country_id bigint unsigned not null,
region_id bigint unsigned not null
Region Model
public function r_countries()
{
return $this->belongsToMany(Country::class, "country_regions","region_id","country_id");
}
Country Model
public function r_regions(): BelongsToMany
{
return $this->belongsToMany(Region::class, "country_regions", "country_id", "region_id");
}
I tied this it works
$region = \App\Models\Country\Region::findOrFail(23);
$region->r_countries()->pluck("countries.title");
You can use
Model::whereHas('relation_name', function($query) use($varname){
$query->where(condition);
})->get()

go-gorm how to express many2many with additional columns

I want to express the following tables in GORM:
CREATE TABLE indexes (
id INTEGER PRIMARY KEY,
name VARCHAR
)
CREATE TABLE services (
id INTEGER PRIMARY KEY,
name VARCHAR
)
CREATE TABLE index_service (
index_id INTEGER REFERENCES indexes(id),
service_id INTEGER REFERENCES services(id),
write_active INTEGER,
PRIMARY KEY (index_id, service_id)
)
After reading through documentations and questions on stack overflow. I still cannot find an answer on how to express the additional column write_active in GORM's DSL
What I got so far is
type Index struct {
ID unit `json:"id" gorm:"primary_key"`
Name string `json:"name" gorm:"not null"`
}
type Service struct {
ID unit `json:"id" gorm:"primary_key"`
Name string `json:"name" gorm:"not null"`
}
However, I do not know how to write the composite table.
you need to create extra model like this:
package database
type IndexService struct {
WriteActive bool `gorm:"not null,DEFAULT false"`
}

OpenJPA: Assign a sequence generated value to ID if null

I am using jpa for persisting my database along with java pojos
#Entity
#Table(schema = "CENTRALSERVICES", name = "APPLICATION")
public class Application {
#Id
#Column(name = "id", nullable = false, length = 128)
private long id;
}
My database is like this:
CREATE TABLE CENTRALSERVICES.APPLICATION(
id bigint(8) NOT NULL, PRIMARY KEY(id));
The problem is that each application object that I persist was having an Id till now, but the requirement changed and now its not guaranteed if Id will be there. I saw something with sequence but I want to assign a sequence generated value only when the Id is null.
How to solve this. Please help
I changed my database schema and now my primary key is autogenerated whereas id for my application object I have created another field which can be null.