I am using sequelize(4.42.0) along with express. I have two tables categories and main_categories which has the following association:
db.main_categories.hasMany(db.categories);
db.categories.belongsTo(db.main_categories);
I tried to get list of all the categories grouped under their main category using following sequelize command:
var _categoryList = await models.main_categories.findAll({include: [{model: models.categories}], group:['main_categories.id']});
res.send({category_list: _categoryList});
The output of the above sequelize code is :
{
"category_list": [
{
"id": 1,
"name": "Physics",
"created_at": null,
"updated_at": null,
"categories": [
{
"id": 1,
"name": "Mechanics",
"created_at": "2019-03-21T03:39:48.000Z",
"updated_at": "2019-03-21T03:39:48.000Z",
"main_category_id": 1
}
]
},
{
"id": 2,
"name": "Chemistry",
"created_at": null,
"updated_at": null,
"categories": [
{
"id": 6,
"name": "General and Physical Chemistry",
"created_at": "2019-03-21T03:42:54.000Z",
"updated_at": "2019-03-21T03:42:54.000Z",
"main_category_id": 2
}
]
},
{
"id": 3,
"name": "Zoology",
"created_at": null,
"updated_at": null,
"categories": []
},
{
"id": 4,
"name": "Botany",
"created_at": null,
"updated_at": null,
"categories": []
}
]
}
The expected output for me was that the categories array inside each main_category would contain details of all the categories falling under the same main category instead of just one as shown in the output above.
My main_categories table with data:
my categories table with data:
So I later found out that as the associations had already been declared we just need to include the model without any groupby clause. So the final code that worked for me was :
var _categoryList = await models.main_categories.findAll({include: [{model: models.categories}]});
Related
I have some JSON parsing in VBA that's driving me nuts. Here's a sample response:
{
"data": [
{
"type": "access_user",
"attributes": {
"name": "Me",
"email": null,
"phone": null,
"department": "",
"status": "current",
"source": null,
"guest_source": null,
"created_at": "2019-08-19T21:45:56Z",
"updated_at": "2019-08-22T03:38:33Z",
"pin": "77005",
"card_number": null
},
"id": "be66e054-5509-4cf6-a5c2-14b85eb25619",
"links": {
"self": "https://api"
}
},
{
"type": "access_user",
"attributes": {
"name": "Day Code",
"email": null,
"phone": null,
"department": null,
"status": "current",
"source": null,
"guest_source": null,
"created_at": "2019-08-21T19:49:29Z",
"updated_at": "2021-06-16T16:08:28Z",
"pin": "12345",
"card_number": null
},
"id": "3a615a3d-eb1c-4973-9e9f-ace5e29ca964",
"links": {
"self": "https://api"
}
}
],
"meta": {
"page": 1,
"per_page": 25,
"total_count": 2,
"total_pages": 1
}
}
Traversing "data" is fine, but when I traverse "attributes" I'm getting a "Type mismatch" error. Here's my code. I'm not seeing anything wrong. Any thoughts?
For Each Item In Response2.Data("data")
UserType = Item("type")
Id = Item("id")
If UserType = "access_user" Then
For Each Nested In Item("attributes")
Name = Nested("name")
status = Nested("status")
PIN = Nested("pin")
Next
End If
Next
Anyone's assistance is greatly appreciated!
The following two lines are equivalent . . .
For Each Nested In Item("attributes")
and
For Each Nested In Item("attributes").Keys()
So, in fact, you're looping through each key within the dictionary. And so your control variable Nested is assigned a string, hence the type mismatch.
Since Item("attributes") returns a dictionary object, you can eliminate the For Each/Next loop, and you can access your items as follows . . .
Name = Item("attributes")("name")
Status = Item("attributes")("status")
PIN = Item("attributes")("pin")
I have JSON files that consists of 10+ records, like the one below.
Example:
[
{
"ID": null,
"entity": "xxx",
"Name": "Abc",
},
{
"ID": null,
"entity": "yyy",
"Name": "efg",
}
]
I want to add a new element "Date": "xx/xx/xx" to every record, like this:
[
{
"ID": null,
"entity": "xxx",
"Name": "Abc",
"Date": "xx/xx/xx"
},
{
"ID": null,
"entity": "yyy",
"Name": "efg",
"Date": "xx/xx/xx"
}
]
The order does not matter.
So far I have something like this:
date = 'xx-xx-xx'
def file(data, json):
with pathlib.Path(json).open('r+') as upfile:
fdata = json.load(upfile)
fdata.append(data)
upfile.seek(0)
json.dump(fdata, updfile)
...
new_ele = {'Date: ': date}
file(new_ele, file.json)
But my result is like this:
[
{
"ID": null,
"entity": "xxx",
"Name": "Abc",
},
{
"ID": null,
"entity": "yyy",
"Name": "efg",
},
{
"Date": "xx-xx-xx"
}
]
How can I get the Date into every single record?
Thank you
Once imported, your json is a list of dictionaries. So go through all list elements (which are dictionaries) and update them with the update method:
def update_json(data, json_path):
with pathlib.Path(json_path).open('r+') as upfile:
fdata = json.load(upfile)
for elt in fdata:
elt.update(data)
upfile.seek(0)
json.dump(fdata, upfile)
I am developing an API Rest based on Django, I have two models:
Album
Track
I am trying to get the right format on this JSON (this is what I am getting now):
[
{
"album": "album-123kj23mmmasd",
"track": {
"id": 6,
"uuid": "2c553219-9833-43e4-9fd1-44f536",
"name": "song name 1",
},
"duration": 2
},
{
"album": "album-123kj23mmmasd",
"track": {
"id": 7,
"uuid": "9e5ef1da-9833-43e4-9fd1-415547a",
"name": "song name 5",
},
"duration": 4
},
This is what I would like to reach, I would like to group by 'albums':
[
{
"album": "album-123kj23mmmasd",
"tracks": [{
"id": 6,
"uuid": "2c553219-9833-43e4-9fd1-44f536",
"name": "song name 1",
"duration": 2
},
{
"id": 7,
"uuid": "9e5ef1da-9833-43e4-9fd1-415547a",
"name": "song name 5",
"duration": 4
},
]
},
]
EDIT 1: I am using Foreign Key instead ManyToMany
class Track(models.Model:
name, creation_date, etc...
class Album(models.Model):
track = models.Foreignkey(Track, on_delete=models.CASCADE)
Thanks in advance
SOLUTION:
Due the model complexity, I decided to user BaseSerializer, which allows to create custom response.
I have JSON column, containing the JSON array. My Scenario, is to get all the the records where value of url is
'"example.com/user1"' is present. I have trouble writing the query for this operation.
Record1
[
{
"id": "1",
"firstname": "user1",
"url": "example.com/user1"
},
{
"id": "2",
"firstname": "user2",
"url": "example.com/user2"
}
]
Record2
[
{
"id": "1",
"firstname": "user3",
"url": "example.com/user3"
},
{
"id": "2",
"firstname": "user2",
"url": "example.com/user2"
}
]
......
......
......
Record10
[
{
"id": "1",
"firstname": "user10",
"url": "example.com/user10"
},
{
"id": "2",
"firstname": "user1",
"url": "example.com/user1"
}
]
The Query Which I ran is:
Select internal_id from users_dummy where JSON_EXTRACT(user_friends, '$[0].url') = "example.com/user1" or JSON_EXTRACT(user_friends, '$[1].url') = "example.com/user1";
So o/p was:
Record1, Record10
Is this the proper way to search for the values across the records?
Thanks in advance.
You can use JSON_SEARCH like this:
SELECT *
FROM users_dummy
WHERE JSON_SEARCH(user_friends, 'one', 'example.com/user1', NULL, '$[*].url') IS NOT NULL
demo on dbfiddle.uk
You can use the following solution in case you are using objects instead of arrays:
SELECT *
FROM users_dummy
WHERE JSON_SEARCH(user_friends, 'one', 'example.com/user1', NULL, '$.*.url') IS NOT NULL
demo on dbfiddle.uk
Update at the end
I have this API for a social media app in iOS builded in Laravel and i've been having problems with the feed section, the Eloquent code for the feed is giving me the wrong id for each posts.
public function feed(){
if (request()->has('page')) {
$pagesize = 20;
$query = Posts::join('clase_user', function ($join) {
$user = JWTAuth::parseToken()->authenticate();
$join->on('clase_user.clase_id', '=', 'posts.clase_id')
->where('clase_user.user_id', '=', $user->id);
})
->with('user')
->skip(((int)request()->get('page') - 1) * $pagesize)
->take($pagesize)->get();
return $query;
}else{
return response()->json(['error' => 'Page not specified'], 500);
}
}
the return is this:
{
"posts": [
{
"id": 3,
"user_id": 1,
"clase_id": 1,
"thumbNail": null,
"text": "Hola Chicos",
"archivo": null,
"created_at": "2017-07-20 00:00:00",
"updated_at": "2017-07-20 00:00:00",
"user": {
"id": 1,
"name": "Juan Carlos",
"about": "Hola me llamo Juan Carlos",
"handler": "Juantvz50",
"pp": null,
"verify": 1,
"email": "jc_estevezr#hotmail.com",
"deleted_at": null,
"LoginId": null,
"created_at": "2017-07-20 23:52:28",
"updated_at": "2017-07-20 23:52:28"
}
},
{
"id": 1,
"user_id": 1,
"clase_id": 2,
"thumbNail": null,
"text": "Que pex Prrrro",
"archivo": null,
"created_at": "2017-07-20 00:00:00",
"updated_at": "2017-07-20 00:00:00",
"user": {
"id": 1,
"name": "Juan Carlos",
"about": "Hola me llamo Juan Carlos",
"handler": "Juantvz50",
"pp": null,
"verify": 1,
"email": "jc_estevezr#hotmail.com",
"deleted_at": null,
"LoginId": null,
"created_at": "2017-07-20 23:52:28",
"updated_at": "2017-07-20 23:52:28"
}
},
{
"id": 3,
"user_id": 1,
"clase_id": 1,
"thumbNail": null,
"text": "Que Onda Chicos",
"archivo": null,
"created_at": "2017-07-20 00:00:00",
"updated_at": "2017-07-20 00:00:00",
"user": {
"id": 1,
"name": "Juan Carlos",
"about": "Hola me llamo Juan Carlos",
"handler": "Juantvz50",
"pp": null,
"verify": 1,
"email": "jc_estevezr#hotmail.com",
"deleted_at": null,
"LoginId": null,
"created_at": "2017-07-20 23:52:28",
"updated_at": "2017-07-20 23:52:28"
}
}
]
}
Even though my database has different ids for each one:
Database
it looks like something is wrong in some part of my code, I don't know in which part if you want to see more code just ask in the comments.
UPDATE
the id it's giving me is in fact the id of the table clase_user that is the pivot table I use to join many to many the classes with the users (like when you follow someone on youtube), I think is because i'm saying Posts::join('clase_user', any ideas to also include the the id of the post?
clase_user
Similar to this one: Join with where query in Laravel returns wrong timestamps
Because of your JOIN the attributes are getting overridden (not only the id but also the created_at/updated_at timestamps). Therefore you should define a select statement for your specific attributes.