Laravel Query Builder pivot table connection - laravel-8

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()

Related

How to display an average in a temp table using data from two tables in postgres

So I have two tables. one table is called Students and the other table is called Grades. I'm trying to figure out how to join both tables together using the students ID from STUDENTS and students id in GRADE to get their actually grade. With that information I want to be able to find the average of all those grades for that student to display their average in a temporary table.
This is my code so far using JavaScript.. Thanks if anybody can help.
const { Client } = require('pg');
const client = new Client({
host: 'localhost',
user: 'postgres',
database: 'xxx',
password : 'xxx',
port: xxx,
});
client.connect();
const createStudents = `
CREATE TABLE students (
name varchar,
id uuid NOT NULL,
email varchar,
age int
);
`;
client.query(createStudents, (err, res) => {
if(err){
console.error(err);
return;
}
console.log("Students have been successfully connected");
})
const createGrades = `
CREATE TABLE grades (
name varchar,
id uuid NOT NULL,
class varchar,
email varchar,
grade int
);
`;
client.query(createGrades, (err,res) => {
if(err){
console.error(err);
return;
}
console.log("Grades have been successfully connected");
client.end();
})
This is in need of a Foreign Key between grades and students. A simple design that I think achieves what you want:
CREATE TABLE students (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name varchar NOT NULL,
email varchar,
age int
);
CREATE TABLE grades (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
student_id integer NOT NULL REFERENCES students ON UPDATE CASCADE,
class varchar NOT NULL,
grade int NOT NULL
);
Then the query:
SELECT
name, avg(grade) AS avg_grade
FROM
grades
JOIN
students
ON
grades.student_id = students.id
GROUP BY
students.id
The FOREIGN KEY eliminates the duplication of information in your original design e.g name and email in the grades table. It all ensures that a grade can only be entered for a student that exists in the students table. The GENERATED ALWAYS AS IDENTITY sets up an automatically incrementing field that can be used as the Primary Key instead of your design which had no declared PK. REFERENCES students will by default use students.id as the referenced column for the values entered in grades.student_id.

how to define many-to-many relationship in prisma/psql

I'm struggling a bunch with some relatively simple Postgres that I was originally trying to define in Prisma but wasn't having much luck. It's a many to many relationship joined on a single field between two tables as such:
CREATE TABLE scheduleDate (
schedule_day_number int NOT NULL
, schedule_date date NOT NULL
,CONSTRAINT scheduledate_pkey PRIMARY KEY (schedule_date, schedule_day_number)
);
CREATE TABLE schoolDayBlock (
start_time varchar(10) NOT NULL
, end_time varchar(10) NOT NULL
,school_block_day_number int NOT NULL
, block_name varchar(10) NOT NULL
,CONSTRAINT schooldayblock_pkey PRIMARY KEY (start_time, end_time, school_block_day_number, block_name )
);
I eventually want to be able to get all the possible combinations between these two tables with the day number fields being the link. Ideally, later down the line, I can query Prisma for a block name and get all of the dates and times where that block name shows up. Does anyone know how I could
Write this up in a Prisma schema or
Write this up in postgres.sql and use introspection to generate a Prisma schema that accomplishes this.
Here's the prisma schema equivalent of your SQL query for creating two tables.
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model scheduleDate {
schedule_day_number Int
schedule_date DateTime
##id([schedule_day_number, schedule_date], name: "scheduledate_pkey")
}
model schoolDayBlock {
start_time DateTime
end_time DateTime
school_block_day_number Int
block_name String
##id([start_time, end_time, school_block_day_number, block_name], name: "schooldayblock_pkey")
}

How to update the nested tables in sql using gorm?

Here the code is written in Go. I am using two tables where one table has a foreign key that refers to the other table's primary key. Let's say I have a database as following struct defined:
type User struct{
ID uint `gorm:"primary_key;column:id"`
Name string `gorm:"column:name"`
Place place
PlaceID
}
type Place struct{
ID uint `gorm:"primary_key;column:id"`
Name string `gorm:"column:name"`
Pincode uint `gorm:"column:pincode"`
}
And the sql schema is:
create table place(
id int(20) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
pincode uint(20) NOT NULL,
PRIMARY KEY (id),
)
create table user(
id int(20) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
place_id uint(20) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (place_id) REFERENCES place(id)
)
Now while inserting in user by gorm as:
place := Place{Name:"new delhi",Pincode:1234}
user := User{Name: "sam", Age: 15, Place: place}
err = db.Debug().Create(&user).Error
//It inserts to both user and place table in mysql
//now while updating to name in user table as Samuel and place as
//following
place := Place{Name:"mumbai",Pincode:1234}
err = db.Debug().Model(&User{}).Where("id =?",
1,).Update(&user{Name:"Samuel",Place:place}).Error
It updates the row in user table but creates a new row in place table.But it should update the matching row in place table and not create a new one
Is there any way to do it? Here I am not using auto migrate function to create db tables.
The answer to your question should be sought in a relations or Association Mode.
The example below shows how to add new associations for many to many, has many, replace current associations for has one, belongs to
db.Model(&user).Association("Place").Append(Place{Name:"mumbai",Pincode:1234})
Or you can replace current associations with new ones:
db.Model(&user).Association("Place").Replace(Place{Name:"mumbai",Pincode:1234},Place{Name:"new delhi",Pincode:1234})
Probably It's creating a new row because you didn't set the ID on Place{Name:"mumbai",Pincode:1234}.

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"`
}

NHibernate Set Property Default Value

Is it possible to set the default value of a property in NHibernate? Here is the scenario:
I have a self join table Category. The class and table structure are as follows:
Category
int Id
string Name
Category ParentCategory
Category
int Id not null
varchar Name not null
int ParentCategoryId not null
If a category has no parent, the ParentCategoryId must be 0.
How do I do this? TIA.
If nHibernate is enforcing this relationship I don't believe you can make it form an invalid relationship. I'd create a dummy parent record 0 in the database and just assign everything to that.
If the ParentCategoryId is not constrained by a foreign key, then you can have in your code ... something like :
class Category{
....
public static Category NoParent{
get{ return new Category{Id = 0}; }
}
....
}
and now, instead of setting to null, just set it to NoParent. Or in the setter of ParentCategory, if value is null, then set it to NoParent.
This is basically Spencer Ruport's ideea :P