Is it possible to create a relation in Typeorm with just an id? - sql

I'm using Nodejs, Typescript, TypeORM, PostgreSQL
I have my relation OneToMany with on one side the most important :
#ManyToOne(() => Group, (groupe) => group.listMember, { eager: true })
readonly group: Group;
Right now my use-case to create a member ask for an ID of the entity Group. When I extract the ID from the request, I have to make a findOneByID to get the entire Group corresponding to the ID I received.
Then I pass it to my Member class to build it from the constructor and then store it in the database with .save() method.
My issue is that I would like to NOT have to retrieve the entire Group object from the database : Since in the end, we just store an ID in the Member table why wouldn't we be able to create the OneToMany or ManyToMany relation just from an ID ?
Do TypeORM offer a way to do it ?
I hope I could translate my issue. Thanks in advance for your help !

Related

How can i specify a hasOne relationship while there are many record in Phalcon

there are two tables,Task and Report
Task(id,name,latest_report_id);
Report(id,content,feedback,task_id);
one task has many report but it only has one latest report.I wanna how can I get this hasOne relationship in Phalcon 4.0
Thanks.
I've never done this, but according to the documentation, you can use conditional relationships. When you set up your relationships in Task:
$this->hasMany("report_id", Report::class, "id");// This is the standard one-to-many
$this->hasMany(
"report_id",
Report::class,
"id",
"params" => [
"order"=>"date_entered DESC",
"limit"=>1
],
"alias" => "LatestReport"
);
This assumes date_entered is the field in the report table you can use to determine which report is the "latest".
https://docs.phalcon.io/4.0/en/db-models-relationships#conditionals
you didn't mention the database engine but in case its mysql, you might in the future set up the relations before making the models and use the Phalcon's cli tool (Devtools) and will setup the relationship in the models for you
to get the latest report from the Task model add this relation in Task model file
$this->belongsTo('latest_report_id', 'Report', 'id', ['alias' => 'latestReport']);
this would lookup Report table using findFirst with id = latest_report_id condition
if this is not the case please update the question with more details

Triple relation QueryBuilder symfony (what the hell am I doing?)

Let me explain how I am making things (maybe not the best way by the way).
I want to join my StoreSchedule entity (which contains a triple relation : store (which is where I stock all informations about adress, name, picture of my stores), days (the 7 days of the week) and Schedules (only strings like '09:00-22:00').
To combine thoses 3 entities, I made StoreSchedule, that has a triple relation where I cross the 3 informations. Maybe I am not explaining well, let me show you some screens.
What I already tried to do with my QueryBuilder in my repository:
https://imgur.com/a/bE52iBH
How I structured things in my StoreSchedule table :
https://imgur.com/a/6m7YkhI
My Schedule table :
https://imgur.com/a/75bRriS
Days table contains the 7 days of the week. Maybe that's obvious, maybe not.
So here's the thing, I can't figure out how to make the I need : a query that gets all content from Store and joins StoreSchedule where ID = Store.ID
I want to get days and Schedule with the ID from store.
Can I do that with query builder?
Do I have to modifiy my database? Are my relations good?
Best regards!
ps : hope I made myself clear enough..
You make it too complicated. You can purge the days table AND StoreSchedule. Just make a many-to-one relation between Store and (Store)Schedule. Add a column "day" in your schedule table. A short integer will do if you store the number of the day. See php's date function.
For your query (the first link) you won't need that WHERE clause. Doctrine will join the related data automatically for you.
public function getAllContentStoreAndSchedule()
{
return $this->createQueryBuilder('st')
->leftJoin('st.schedule', 'sc')
->addSelect('sc')
->orderBy('st.name', 'ASC')
->addOrderBy('sc.day', 'ASC')
->getQuery()
;
}

Mass/bulk update in rails without using update_all with a single query?

I want to update multiple rows using single query of active record. I don't have to use update_all because it skips validation. Is there any way to do this in rails active record.?
Mass update without using update_all can be achievable using activerecord-import gem.
Please refer to this gem for more information.
Methods with detail.
Example:
Lets say there is a table named "Services" having a "booked" column. We want to update its value using the gem outside the loop.
services.each do |service|
service.booked = false
service.updated_at = DateTime.current if service.changed?
end
ProvidedService.import services.to_ary, on_duplicate_key_update: { columns: %i[booked updated_at] }
active-record import by default does not update the "updated_at" column. So we've to explicitly update it.
If you want to update multiple records without instantiating the models, update_all method should do the trick:
Updates all records in the current relation with details given. This method constructs a single SQL UPDATE statement and sends it straight to the database. It does not instantiate the involved models and it does not trigger Active Record callbacks or validations. However, values passed to #update_all will still go through Active Record’s normal type casting and serialization.
E.g:
# Update all books with 'Rails' in their title
Book.where('title LIKE ?', '%Rails%').update_all(author: 'David')
As I understood, it even accepts an array as a parameter, allowing us to provide different hashes to update different records in their corresponding order, like in SQL UPDATE statement. Correct me, somebody, if I'm wrong.
It sounds like you are looking for Update records - from the documentation Updating multiple records; different col with different data
You can do like this Example:
people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
Person.update(people.keys, people.values)

Sequelize - Incorporate stores into retailers after obtaining the latter

I'm really new to Sequelize and I find the Docs confusing especially for my case since I already had a Postgres DB set up and used sequelize-auto to create all the models from the existing DB.
Now I have the following:
Retailers
Stores
Stores have a FK in retailer_id since Retailers have several Stores, but a single Store belongs to a single Retailer.
I want to retrieve from my Node API a JSON with the following format:
[{
id:"1",
name: "RetailerName",
stores: [{
id: "1",
name: "StoreName",
...
}]
}]
I was thinking of getting all of the retailers, iterate through them and getting all stores based on the "current" retailer id and adding them to retailers, replying that.
However this is not possible without a promise of some sort and since there are better tools to achieve this with sequelize I would like to know how to do this!
Use sequelize's associations (One-To-Many in this particular case)

Django Filter items with OneToOne relationship to Group of Users

In Django, if I have a model such as a Building which is OneToOne related to a (Django Auth) Group containing users, how can I find all the buildings to User belongs to (maybe those are all the buildings the User works in)? Building is one to one with Group so building has a group foreign key field called 'group'.
I've tried
Building.objects.filter(group__contains=user)
Building.objects.filter(group_user_set__contains=user)
I'm getting no matches when there should be matches.
Using contains is not the right choice since it searches for expression inside field (string) not within the set. Try using:
Buildings.objects.filter(group__user=user)
If it's a one to one relationship why not just return the groups?
result = []
u = User.objects.get(your user here)
for group in u.groups.all():
result.append(group.whateverYourForeignKeyFieldIsCalled)
return result