I am trying to order only the nested include Scheme Model based on an integer column but it seems like the code is not working. Also, the data is being fetched from MYSQL bottom to up and shown as output.
sample code:
[err, products] = await to(
Product_Inventory_Mapping.findAll({
include: [
{
model: Product,
as: "product_details",
where: filterClause,
include: [
{
model: Unit,
as: "unit_details"
},
{
model: Brand,
as: "brand_details"
},
{
model: Category,
as: "category_details"
},
{
model: Sub_Brand,
as: "sub_brand_details"
},
{
model: Sub_Category,
as: "sub_category_details"
},
{
model: Brand_Company,
as: "brand_company_details"
},
{
model: Scheme,
as: "schemes",
attributes: [`moq`, 'discount', `description`],
order: [[{ model: Scheme, as: "schemes" }, "moq", "ASC"]],
where: {
status: 1
},
required: false
}
]
}
],
order: [
[{ model: Product, as: "product_details" }, "mrp", "ASC"]
],
where: {
user_id: aligned_distributors,
brand_company_id: filtered_brand_company,
count: {
[Op.gt]: 0
},
sp: {
[Op.gt]: 0
}
},
attributes: [
`product_id`,
"user_id",
"count",
"sp",
"occ",
"brand_company_id"
],
limit: limit,
offset: offset,
subQuery: false
}));
Here I want to order only the data inside the Scheme Model.
Sample response:
"products": [
{
"product_id": 115,
"user_id": 1003,
"count": 50,
"sp": 9.09,
"occ": 9.09,
"brand_company_id": 11,
"product_details": {
"id": 115,
"category_id": 2,
"sub_category_id": 12,
"brand_company_id": 11,
"brand_id": 24,
"sub_brand_id": 44,
"sku_code": null,
"min_order_qty": "27",
"description": "Nandini Butter Milk Tetra Pack, 200 Ml",
"unit_id": 4,
"weight": "200ml",
"mrp": "10.00",
"barcode": "",
"image_url": "https://xxxxxx.s3.ap-south-1.amazonaws.com/products/1565919229Unknown-min-5.jpg",
"created_at": "2019-08-12T13:44:01.000Z",
"updated_at": "2019-08-15T20:03:49.000Z",
"unit_details": {
"id": 4,
"name": "Pieces",
"created_at": null,
"updated_at": null
},
"brand_details": {
"id": 24,
"name": "Nandini Butter Milk",
"brand_company_id": 11,
"created_at": null,
"updated_at": null
},
"category_details": {
"id": 2,
"name": "Packaged Food",
"image_url": "https://zzzz.s3.ap-south-1.amazonaws.com/images/category/food-min.png",
"created_at": "2019-08-11T11:36:52.000Z",
"updated_at": "2019-08-11T11:36:52.000Z"
},
"sub_brand_details": {
"id": 44,
"name": "Nandini Butter Milk",
"brand_id": 24,
"created_at": null,
"updated_at": null
},
"sub_category_details": {
"id": 12,
"name": "Dairy products (Butter, Cheese etc)",
"category_id": 2,
"created_at": null,
"updated_at": null
},
"brand_company_details": {
"id": 11,
"name": "Karnataka Co-operative Milk Producers",
"image_url": "https://xxxxx.s3.ap-south-1.amazonaws.com/images/company/kmf_logo.jpg",
"created_at": "2019-08-12T13:10:18.000Z",
"updated_at": "2019-08-12T13:10:18.000Z"
},
"schemes": [
{
"moq": 30,
"discount": 1.5,
"description": "8 % offer"
},
{
"moq": 20,
"discount": 1,
"description": "20 % offer"
},
{
"moq": 40,
"discount": 2,
"description": "40 % offer"
}
]
}
}]
In the database, the Scheme data is saved as:
Scheme belongs to the Product via product_id. I want the Scheme array to be sorted by moq ASC so that the value comes in order of moq: 20 > 30 > 40.
AFAIK, an order clause in the included model doesn't work. But, you can make a reference to the included model in the main model. I think this should work if you combine your two order clauses into one:
Product_Inventory_Mapping.findAll({
include: [
..... lots of includes here ....
],
order: [
[{ model: Product, as: "product_details" }, "mrp", "ASC"],
[{ model: Scheme, as: "schemes" }, "moq", "ASC"]]
],
This will order by moq within mrp... you could remove the first field if you really want to sort ONLY by moq....
Related
I got a collection but I want to sort that collection. If the two application's cgpa is equal then sort the list collection according to the annual_salary where lower will up at list. Default the collection sort with the cgpa. below is my server response.
Thanks in advance
"applications": [
{
"id": 1,
"name": "Dr. W Khan",
"annual_salary": 5000,
"created_at": "2022-11-07T19:16:01.000000Z",
"updated_at": "2022-11-07T19:16:01.000000Z",
"education": [
{
"id": 1,
"application_id": 1,
"name": "HSC",
"cgpa": 400,
"created_at": "2022-11-07T19:16:01.000000Z",
"updated_at": "2022-11-07T19:16:01.000000Z"
}
]
},
{
"id": 2,
"name": "Dr. M Khan",
"annual_salary": 7000,
"created_at": "2022-11-07T19:16:14.000000Z",
"updated_at": "2022-11-07T19:16:14.000000Z",
"education": [
{
"id": 2,
"application_id": 2,
"name": "HSC",
"cgpa": 350,
"created_at": "2022-11-07T19:16:14.000000Z",
"updated_at": "2022-11-07T19:16:14.000000Z"
}
]
},
{
"id": 3,
"name": "Dr.",
"annual_salary": 5000,
"created_at": "2022-11-07T19:16:28.000000Z",
"updated_at": "2022-11-07T19:16:28.000000Z",
"education": [
{
"id": 3,
"application_id": 3,
"name": "HSC",
"cgpa": 350,
"created_at": "2022-11-07T19:16:28.000000Z",
"updated_at": "2022-11-07T19:16:28.000000Z"
}
]
}
]
This is the query for me.
$application = Application::with(
[
'education' => function ($query) {
$query->orderBy('cgpa', 'desc');
},
]
)
->orderBy('annual_salary', 'asc')
->get();
But ordering the list followed by a second orderBy.
I was trying to SUM an Review Score on association (relational) table between Post & UserReviews using MySQL, I had SQL like this.
sql
SELECT SUM(`score`) / COUNT(`scoreableId`) FROM `UserReviews` GROUP BY `scoreableId`;
I want convert it into sequelize query builder, I had try like this.
sequelize
db.Post.findAndCountAll({
attributes: [
'id',
],
include: [{
model: db.PostAttribute,
as: 'attributes',
attributes: [
'title',
'description',
],
order: [
['updatedAt', sort.includes('date') ? 'ASC' : 'DESC'],],
include: [{
model: db.PostPhoto,
attributes: ['url'],
as: 'photos'
}, {
model: db.UserReview,
as: 'reviews',
attributes: [
'scoreableId',
[db.sequelize.fn('SUM', db.sequelize.col('rating')), 'rating']
],
group: ['scoreableId']
}]
}],
})
But resulting output from those query was whole SUM of RATING (all users rating as single) inside single row.
{
"data": [
{
"id": 1,
"attributes": {
"title": "Tasty Frozen Salad",
"description": "description goes here",
"photos": [
{
"url": "https://loremflickr.com/500/650/fashion?47655"
}
],
"reviews": [
{
"scoreableId": 1,
"rating": "392"
}
]
}
}
]
}
I was expecting it result were rather like this.
{
"data": [
{
"id": 1,
"attributes": {
"title": "Tasty Frozen Salad",
"description": "description goes here",
"photos": [
{
"url": "https://loremflickr.com/500/650/fashion?47655"
}
],
"reviews": [
{
"scoreableId": 1,
"rating": "50"
}
]
}
},
{
"id": 2,
"attributes": {
"title": "Another Tasty Frozen Salad",
"description": "description goes here",
"photos": [
{
"url": "https://loremflickr.com/500/650/fashion?47655"
}
],
"reviews": [
{
"scoreableId": 2,
"rating": "40"
}
]
}
}
]
}
i want to calculate the total costs of products selected by a user under each company.There is my code.
let companiesProductPrices = [];
let prices = [];
this.selectedCompaniesDetails.forEach(company => {
this.chosenItems.forEach(item=> {
item.product_attributes.forEach(product => {
if(company.id == product.company_id)
{
prices.push(product.price);
companiesProductPrices[company.id] = prices;
}
})
});
})
Background information. I have to objects. The products object and the companies object.
Products object referred to as this.chosenItems in my code and is like this;
[
{
"id": 1,
"name": "Zimgold",
"slug": null,
"product_category_id": 1,
"industry_id": 1,
"category": {
"id": 1,
"name": "Cooking Oil",
"slug": null,
"industry_id": 1
},
"product_attributes": [
{
"id": 1,
"description": "2 litres",
"discount": null,
"price": "120",
"tax": null,
"company_id": 1,
"product_id": 1
},
{
"id": 5,
"description": "2 litres",
"discount": null,
"price": "130",
"tax": null,
"company_id": 2,
"product_id": 1
}
]
},
{
"id": 4,
"name": "Silo",
"slug": null,
"product_category_id": 3,
"industry_id": 1,
"category": {
"id": 3,
"name": "Mealie Meal",
"slug": null,
"industry_id": 1
},
"product_attributes": [
{
"id": 4,
"description": "10 kgs",
"discount": null,
"price": "130",
"tax": null,
"company_id": 1,
"product_id": 4
}
]
}
]
and my company object referred to as this.selectedCompaniesDetails in my code and is like this.
[
{
"id": 1,
"name": "Spar",
"slug": null,
"industry_id": 1
},
{
"id": 2,
"name": "Ok",
"slug": null,
"industry_id": 1
},
{
"id": 3,
"name": "TM",
"slug": null,
"industry_id": 1
},
{
"id": 4,
"name": "choppies",
"slug": null,
"industry_id": 1
},
{
"id": 5,
"name": "Bon Marche",
"slug": null,
"industry_id": 1
}
]
I'm wishing to get the totals of all products that are belong to each company. Let me show you my UI.
So what i want is under spar the total should be 250 and under 130 and so forth for all other companies. Thank you in advance
This is one of many solutions. It's improvable, it's just to show you the way.
#1 Create an object where key is company id and value is the array of prices for that company
const priceByCompany = products.reduce((tot, prod) => {
prod.product_attributes.forEach((p) => {
if (!tot[p.company_id]) {
tot[p.company_id] = []
}
const numberPrice = parseInt(p.price, 10)
tot[p.company_id].push(numberPrice)
})
return tot
}, {})
// { 1: [120, 130], 2: [130] }
#2 Reduce all value array to sum them up.
Object.keys(priceByCompany).forEach((company) => {
const total = priceByCompany[company].reduce((tot, price) => tot + price, 0)
priceByCompany[company] = total
})
// { 1: 250, 2: 130 }
See the code in action: Jsfiddle
Hoping for some pointers here as I'm striking out with my attempts. Am working with python 3.8.5.
I'm querying a Car Park booking system that returns a json list of availability. The result has lots of nested dictionaries and I'm struggling to extract just the values i want.
This is what I've been doing:
import requests
import json
enquiry = requests.post(url.....) #queries api, this works fine
results = enquiry.text #extracts response data
dictionary = json.loads(results) #convert response to python dict
If there is one slot available, I get this output (apologies for length). If there are multiple slots available, i get the same output repeated:
{
"data": {
"services": [{
"id": null,
"name": null,
"services": [{
"id": null,
"name": "Car Park",
"met": true,
"filterCount": 1,
"primary": true,
"options": [{
"id": "9",
"images": [],
"available": true,
"calendarId": "AAAA",
"templateId": "BBBB",
"capacity": 0,
"name": "Car Park Slot 3",
"sessionId": "CCCC",
"functions": null,
"startDate": "2020-08-18T13:30:00Z", <--this is what I want to extract
"endDate": "2020-08-18T14:30:00Z",
"geo": {
"lat": 0.0,
"lng": 0.0
},
"selected": false,
"linkedServices": [],
"tiers": null
}]
}],
"currentBookingId": null,
"startDate": {
"ms": 1597757400000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 14,
"days": 0
}
},
"endDate": {
"ms": 1597761000000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 15,
"days": 0
}
},
"sessionId": "2222222",
"chargeType": 1,
"hasPrimaryBookable": false,
"hasBookable": false,
"hasDiscounts": false,
"hasMultipleTiers": false,
"isPreferred": false,
"primaryServiceAvailable": true,
"primaryServiceId": null,
"primaryServiceType": "undefined",
"unavailableAttendees": []
}],
"bookingLimit": null
},
"success": true,
"suppress": false,
"version": "2.3.293",
"message": null,
"result": null,
"errors": null,
"code": null,
"flags": 0,
"redirect": null
}
I want to extract:
"startDate": "2020-08-18T13:30:00Z"
from each key, value pair in any of the returned slots. However, I cant work it out.
Extracting the whole of this nested dictionary would also contain the same data, but would then involve more work to tidy it up after.
"startDate": {
"ms": 1597757400000,
"year": 2020,
"month": 8,
"day": 18,
"dayOfWeek": 2,
"time": {
"seconds": 0,
"minutes": 30,
"hours": 14,
"days": 0
}
I've tried loads of dictionary.get and dictionary.items variations, but cant seem to get anywhere.
I tried something like
key = ('startDate')
availability = dictionary.get(key)
print(availability)
this just returns 'none', so think im way off
Any pointers?
Thanks in advance!
Thanks for the full data. It makes testing easier :)
I had to replace null -> None, true -> True, false -> False
slot = {
"data": {
"services": [{
"id": None,
"name": None,
"services": [{
"id": None,
"name": "Car Park",
"met": True,
"filterCount": 1,
"primary": True,
"options": [{
"id": "9",
"images": [],
"available": True,
"calendarId": "AAAA",
"templateId": "BBBB",
"capacity": 0,
"name": "Car Park Slot 3",
"sessionId": "CCCC",
"functions": None,
"startDate": "2020-08-18T13:30:00Z", # <--this is what I want to extract
................
print("Start Date:", slot['data']['services'][0]['services'][0]['options'][0]['startDate'])
Output
Start Date: 2020-08-18T13:30:00Z
My mule code is hitting two tables and getting some details.
First one is order details, which I am storing in a flow variable i.e order and another database is returning order item details which I am storing in orderitem variable.
I want to aggregate both the payload based on one condition. Every orderId has order items (which is stored in flowVars.orderitem) and map these order items to respective orderID.
flowVars.order value is as below
[{partnerId=e83185e9f33e4234ba9eaa81dba515ad, orderId=12345, orderDate=2017-02-28 16:41:41.0, id=22}, {partnerId=e83185e9f33e4234ba9eaa81dba515ad, orderId=123456, orderDate=2017-02-28 16:41:41.0, id=23}, {partnerId=e83185e9f33e4234ba9eaa81dba515ad, orderId=11111, orderDate=2017-02-28 16:41:41.0, id=24}, {partnerId=e83185e9f33e4234ba9eaa81dba515ad, orderId=321123, orderDate=2017-05-19 15:25:41.0, id=26}]
and flowVars.orderitem value is as below
[{productCode=ELT-LP-ICND1-020067, orderId=12345, quantity=10, id=14}, {productCode=ELT-IP-ICND1-1.0, orderId=12345, quantity=11, id=15}, {productCode=ELT-LP-ICND1-020067, orderId=123456, quantity=12, id=16}, {productCode=ELT-IP-ICND1-1.0, orderId=123456, quantity=13, id=17}, {productCode=ELT-LP-ICND1-020067, orderId=11111, quantity=14, id=18}, {productCode=ELT-IP-ICND1-1.0, orderId=11111, quantity=15, id=19}, {productCode=ELT-LP-ICND2-020067, orderId=321123, quantity=5, id=20}]
Expected Output
[
{
"orderId": "12345",
"orderDate": "2017-02-28T16:41:41",
"partnerId": "e83185e9f33e4234ba9eaa81dba515ad",
"orderItems": [
{
"productCode": "ELT-LP-ICND1-020067",
"quantity": "10"
},
{
"productCode": "ELT-IP-ICND1-1.0",
"quantity": "11"
}
]
},
{
"orderId": "123456",
"orderDate": "2017-02-28T16:41:41",
"partnerId": "e83185e9f33e4234ba9eaa81dba515ad",
"orderItems": [
{
"productCode": "ELT-LP-ICND1-020067",
"quantity": "12"
},
{
"productCode": "ELT-IP-ICND1-1.0",
"quantity": "13"
}
]
},
{
"orderId": "11111",
"orderDate": "2017-02-28T16:41:41",
"partnerId": "e83185e9f33e4234ba9eaa81dba515ad",
"orderItems": [
{
"productCode": "ELT-LP-ICND1-020067",
"quantity": "14"
},
{
"productCode": "ELT-IP-ICND1-1.0",
"quantity": "15"
}
]
},
{
"orderId": "321123",
"orderDate": "2017-05-19T15:25:41",
"partnerId": "e83185e9f33e4234ba9eaa81dba515ad",
"orderItems": [
{
"productCode": "ELT-LP-ICND1-020067",
"quantity": "5"
}
]
}
]
Here I need to show respective order item details of an order. So basically I need to combine both the payloads.
I tried using dataweave but not luck.
Dataweave code:
%dw 1.0
%output application/json
%var mergeddata = flowVars.orderitem groupBy $.orderId
---
flowVars.order map ((data,index) ->
{
orderid: data.orderId,
partnerid: data.partnerId,
orderdate: data.orderDate,
order: flowVars.orderitem default [] map ((data1 ,indexOf) ->
{
(productcode: data1.productCode) when (data1.orderId == data.orderId),
(quantity: data1.quantity) when (data1.orderId == data.orderId) ,
(id: data1.id) when (data1.orderId == data.orderId)
}
)})
And output after transformation:
{
"orderid": "12345",
"partnerid": "e83185e9f33e4234ba9eaa81dba515ad",
"orderdate": "2017-02-28T16:41:41",
"order": [
{
"productcode": "ELT-LP-ICND1-020067",
"quantity": 10,
"id": 14
},
{
"productcode": "ELT-IP-ICND1-1.0",
"quantity": 11,
"id": 15
},
{
},
{
},
{
},
{
},
{
}
]
},
{
"orderid": "123456",
"partnerid": "e83185e9f33e4234ba9eaa81dba515ad",
"orderdate": "2017-02-28T16:41:41",
"order": [
{
},
{
},
{
"productcode": "ELT-LP-ICND1-020067",
"quantity": 12,
"id": 16
},
{
"productcode": "ELT-IP-ICND1-1.0",
"quantity": 13,
"id": 17
},
{
},
{
},
{
}
]
},
{
"orderid": "11111",
"partnerid": "e83185e9f33e4234ba9eaa81dba515ad",
"orderdate": "2017-02-28T16:41:41",
"order": [
{
},
{
},
{
},
{
},
{
"productcode": "ELT-LP-ICND1-020067",
"quantity": 14,
"id": 18
},
{
"productcode": "ELT-IP-ICND1-1.0",
"quantity": 15,
"id": 19
},
{
}
]
},
{
"orderid": "321123",
"partnerid": "e83185e9f33e4234ba9eaa81dba515ad",
"orderdate": "2017-05-19T15:25:41",
"order": [
{
},
{
},
{
},
{
},
{
},
{
},
{
"productcode": "ELT-LP-ICND2-020067",
"quantity": 5,
"id": 20
}
]
}
]
As you can see that I am almost there and able to map order item details with respective orderId but still I am getting some blank values after transformation.
Can anyone help me to achieve expected output. Thanks in advance!!!
You need to filter the flowVars.orderitem map, rather than iterate it in full and only print values when the orderId matches.
order: ((flowVars.orderitem default []) filter (data.orderId == $.orderId)) map ((data1 ,indexOf) -> {
productcode: data1.productCode,
quantity: data1.quantity
id: data1.id
})
You can then remove all of those 'when' statements too.