What is the correct way to specify eager: true for a one-to-one relationship - typeorm

What is the correct way to specify eager: true for a one-to-one relationship? Failed: order.entity.ts:
#OneToOne(() => HistoryStatusYd)
#JoinColumn( {eager: true} ) historyStatusYd: HistoryStatusYd;
В HistoryStatusYd I don’t do anything for communication, as in the example: https://typeorm.io/one-to-one-relations Found this: Typeorm eager loading not working on one to one relationship
But it doesn't work
Tried it like this:
order.entity.ts:
#Entity()
export class HistoryStatusYd extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#OneToOne(() => Order, (order) => order.historyStatusYd, { eager: true })
order: Order;
…
history-status-yd.ts:
#Entity()
export class HistoryStatusYd extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#OneToOne(() => Order, (order) => order.historyStatusYd, { eager: true })
order: Order;
...
Tried to move { eager: true } to order.entity.

Related

ROR Self Join for self reference

I am using the Self Joins to add reference to its own table.
class Employee < ApplicationRecord
belongs_to :manager, class_name: "Employee", optional: true
has_many :customers
end
class Customer
belongs_to :employee
end
I am fetching the employee data based. One employee will have one employee_head and employee_head will have a boss.
In the serializer i have
class EmployeeSerializer < ApplicationSerializer
# include FastJsonapi::ObjectSerializer
attributes :id, :name, :manager
def manager
ActiveModel::SerializableResource.new(object.manager)
end
end
when i query form employee, i am expecting:
{
employee:
{
id: 1,
name: "employee name",
customer_attributes: [
{ id: 8, name: customer_name }
],
manager: {
id: 2,
name: "employee head name",
customer_attributes: [
{ id: 8, name: customer_name }
],
manager: {
id: 3,
name: "boss name",
customer_attributes: [
{ id: 8, name: customer_name }
],
}
}
}
}
I am getting the expected data using:
Employee.includes(:customers).where(name: "employee name", employee_type: employee)
but the problem is when i hit the query, the customer information is fetched from the database multiple time. I am confuse where to use includes to avoid N+1 query to DB.
Thanks in advance

How to query more fields on mongo DB aggregation query?

I would like to know how to add an extra field to the response of collection.aggregate?
The query below groups activities by user_id. And I would like to know how to also include the user_name in the response.
DB Models
class Activity
include Mongoid::Document
field :hd_race_id, type: Float
field :metric_elapsed_time, type: Float
field :metric_distance, type: Float
field :user_name, type: String
belongs_to :user
...
class User
include Mongoid::Document
field :user_name, type: String
has_many :activities
...
Query
Activity.collection.aggregate([
{
"$group" => {
"_id" => "$user_id",
"distance" => { "$sum" => "$metric_distance" },
"time" => { "$sum" => "$metric_elapsed_time" },
},
},
{ "$sort" => { "distance" => -1 } },
])
Thank you in advance
Use the operator $first (aggregation accumulator) inside the $group stage.
For example:
"user_name": {"$first": "$user_name"}
or for the programming language you are using (not sure what it is), try something like:
"user_name" => {"$first" => "$user_name"},
For an example, see the "Group & Total" chapter in my Practical MongoDB Aggregations book

How to order by field of embedded model in embeds_many mongoid rails application?

I have model Transactions that embeds many Events
class Transaction
embeds_many :events
end
Model Events has fields :name and :execute_at
class Event
field :name, type: String
field :execute_at, type: Date
embedded_in :transaction, inverse_of: :events
end
What I need to do is to sort Transactions by execute_at field of Events with specific name (lets say 'Name1'). Events are unique within each Transaction so there is no issue here.
Example:
{
amount: '123',
events: [
{
name: 'Name1',
execute_at: someday
},
{
name: 'Name5',
execute_at: someotherday
}
}
Transaction2
{
amount: '124',
events: [
{
name: 'Name1',
execute_at: someotherday
},
{
name: 'Name11',
execute_at: somerday
}
}
Basically sort these 2 transactions only taking data for sorting from events with name: 'Name1'
sorted_trans = Transaction.where('events.name' => 'Name1').order_by(:'events.execute_at'.asc)
or
sorted_trans = Transaction.where('events.name' => 'Name1').order_by(:'events.execute_at'.desc)

Mongoid Group By or MongoDb group by in rails

I have a mongo table that has statistical data like the following....
course_id
status which is a string, played or completed
and timestamp information using Mongoid's Timestamping feature
so my class is as follows...
class Statistic
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paranoia
field :course_id, type: Integer
field :status, type: String # currently this is either play or complete
I want to get a daily count of total # of plays for a course. So for example...
8/1/12 had 2 plays, 8/2/12 had 6 plays. Etc. I would therefore be using the created_at timestamp field, with course_id and action. The issue is I don't see a group by method in Mongoid. I believe mongodb has one now, but I'm unsure of how that would be done in rails 3.
I could run through the table using each, and hack together some map or hash in rails with incrementation, but what if the course has 1 million views, retrieving and iterating over a million records could be messy. Is there a clean way to do this?
As mentioned in comments you can use map/reduce for this purpose. So you could define the following method in your model ( http://mongoid.org/en/mongoid/docs/querying.html#map_reduce )
def self.today
map = %Q{
function() {
emit(this.course_id, {count: 1})
}
}
reduce = %Q{
function(key, values) {
var result = {count: 0};
values.forEach(function(value) {
result.count += value.count;
});
return result;
}
}
self.where(:created_at.gt => Date.today, status: "played").
map_reduce(map, reduce).out(inline: true)
end
which would result in following result:
[{"_id"=>1.0, "value"=>{"count"=>2.0}}, {"_id"=>2.0, "value"=>{"count"=>1.0}}]
where _id is the course_id and count is the number of plays.
There is also dedicated group method in MongoDB but I am not sure how to get to the bare mongodb collection in Mongoid 3. I did not have a chance to dive into code that much yet.
You may wonder why I emit a document {count: 1} as it does not matter that much and I could have just emitted empty document or anything and then always add 1 to the result.count for every value. The thing is that reduce is not called if only one emit has been done for particular key (in my example course_id has been played only once) so it is better to emit documents in the same format as result.
Using Mongoid
stages = [{
"$group" => { "_id" => { "date_column_name"=>"$created_at" }},
"plays_count" => { "$sum" => 1 }
}]
#array_of_objects = ModelName.collection.aggregate(stages, {:allow_disk_use => true})
OR
stages = [{
"$group" => {
"_id" => {
"year" => { "$year" => "$created_at" },
"month" => { "$month" => "$created_at" },
"day" => { "$dayOfMonth" => "$created_at" }
}
},
"plays_count" => { "$sum" => 1 }
}]
#array_of_objects = ModelName.collection.aggregate(stages, {:allow_disk_use => true})
Follow the links below to group by using mongoid
https://taimoorchangaizpucitian.wordpress.com/2016/01/08/mongoid-group-by-query/
https://docs.mongodb.org/v3.0/reference/operator/aggregation/group/

sfWidgetFormDoctrineChoiceGrouped render

for my categorie table:
Categorie:
actAs:
Timestampable: ~
Sluggable:
fields: [nom]
NestedSet: ~
columns:
parent_id: { type: integer(8), notnull: false}
nom: { type: string(255), notnull: true, unique: true }
relations:
CategorieParent: { onDelete: SET NULL, local: parent_id, class: Categorie, foreign: id, foreignAlias: CategorieEnfants}
i've add to my form a sfWidgetFormDoctrineChoiceGrouped with this configuration:
'categorie' => new sfWidgetFormDoctrineChoiceGrouped(
array(
'group_by' => 'parent',
'order_by' => array('parent_id',''),
'model' => 'Categorie',
'multiple' => true,
'method' => 'getNom',
)),
In the render i want to have
Categoire with no parent 1
- child categroie
- child categorie..
Categoire with no parent 2
- child categroie
- child categorie..
but in my case i have a render with:
Categoire with no parent 1
Categoire with no parent 2
Categoire with no parent 3
Categoire with no parent 1
- child categroie
- child categorie..
Thank you
There are some mistakes in your options:
'group_by' => 'CategorieParent',
'order_by' => array('parent_id','ASC'),
group_by have to be The name of the relation to use for grouping. I think you can also use parent_id for the group_by option.

Resources