Creating new model with association but without parent instance - node.js

I have these model.
var User = this.sequelize.define('user', {name: String})
var Account = this.sequelize.define('account', {account: String})
User.hasMany(Account);
Account.belongsTo(User);
Now, assume that in TABLE User, i already have:
| id | name |
|----|--------|
| 1 | Maat |
| 2 | MatieL |
Now, i want to create an account but i only want to use User ID not user instance.
Account.create({name: 'MyAccount', userid: 1});
But after that, the row show in TABLE Account is:
| id | account |userId|
|----|-------------|------|
| 1 | MyAccount | NULL |
I don't know why it doesn't work. Please suggest me if you know the answer.
Thank you.
PS:
I know that i can create account instance by another way by firstly finding userinstance by userid then after create account then call userinstance.addAccount(account), but i don't want to use that way because it cost more queries.
PS2: The solution is userId with i capital, not userid

Hi The default foregin key is user_id and not userid
Refer http://docs.sequelizejs.com/en/1.7.0/docs/associations/#foreign-keys

Related

Fetch Last Login Details using Summarize by Time Stamp in KQL

I am trying to get last login details of user in Kusto database using KQL query language. However I am not getting exact result with below query.
GlobalID - Unique GUID Value which will be created every time user logged in
UserId - Logged in UserId value
LastSuccessFullLoginTimeStamp - Max Timestamp value
//Fetch Last Logged in userID details
let window = 2h;
Events
| where Timestamp >= ago(window)
| extend UserId = tostring(Properties.UserId)
| where UserId in ('12345','56789','24680')
//| summarize LastSuccessFullLoginTimeStamp = max(Timestamp), count() by
GlobalId,UserId
|project GlobalID,UserId,TimeStamp
But I am failed to get output as like below from above sample data. Fetch latest GlobalID based on userId and last logged in time. Where I am doing wrong? I tried with summarize, make_set but in vain.
You should use the arg_max() function:
let window = 2h;
Events
| where Timestamp >= ago(window)
| extend UserId = tostring(Properties.UserId)
| where UserId in ('12345','56789','24680')
| summarize arg_max(Timestamp, *) by UserId

Grafana azure log analytics transfer query from logs

I have this query that works in Azure logs when i set the scope to the specific application insights I want to use
let usg_events = dynamic(["*"]);
let mainTable = union pageViews, customEvents, requests
| where timestamp > ago(1d)
| where isempty(operation_SyntheticSource)
| extend name =replace("\n", "", name)
| where '*' in (usg_events) or name in (usg_events)
;
let queryTable = mainTable;
let cohortedTable = queryTable
| extend dimension =tostring(client_CountryOrRegion)
| extend dimension = iif(isempty(dimension), "<undefined>", dimension)
| summarize hll = hll(user_Id) by tostring(dimension)
| extend Users = dcount_hll(hll)
| order by Users desc
| serialize rank = row_number()
| extend dimension = iff(rank > 5, 'Other', dimension)
| summarize merged = hll_merge(hll) by tostring(dimension)
| project ["Country or region"] = dimension, Counts = dcount_hll(merged);
cohortedTable
but trying to use the same in grafana just gives an error.
"'union' operator: Failed to resolve table expression named 'pageViews'"
Which is the same i get in azure logs if i dont set the scope to the specific application insights resource. So my question is. how do i make it so grafana targets this specific scope inside the logs? The query jsut gets the countries of the users that log in
As far as I know, Currently, there is no option/feature to add Scope in Grafana.
The Scope is available only in the Azure Log Analytics Workspace.
If you want the Feature/Resolution, please raise a ticket in Grafana Community where all the issues are officially addressed.

Azure AppInsights query union

I've been writing some queries against AppInsights and noticed that in my data there's 2 ways of determining if a username exists against the telemetry.
customEvents
| where tostring(parse_json(tostring(customDimensions)).username) != '' or tostring(parse_json(tostring(customDimensions.Properties)).username) != ''
| project
Username = tostring(parse_json(tostring(customDimensions)).username),
timestamp = timestamp
| distinct Username, bin(timestamp, 1d)
| summarize count() by bin(timestamp, 1d)
| render timechart
Bit stuck, notice in the first where there's 2 ways of determing whether a record is valid, how do I change the projection to then say "if username is here, take it from here, else check in customDimensions.Properties
I assume we need a union from somewhere?
you could use the coalesce() function:
datatable(customDimensions: string)
[
'{"username": "user1"}',
'{"Properties": {"username": "user2"}}'
]
| where customDimensions has 'username'
| extend cd = parse_json(customDimensions)
| project UserName = tostring(coalesce(cd.username, cd.Properties.username))
| where isnotempty(UserName)
Username
user1
user2

How to Dynamically assemble SQL queries with haskell based on route parameters

I've got a scotty web app that I am trying to implement a dynamic search interface over and keep hitting a wall on how I should implement it. The Basic premise is the following:
Given a list of URL parameters: let params = [Param]
where param: type Param = (Text, Text)
I would like to be able to
Lets say I have a table in my database where:
Users
| user_id | username | email | first_name | last_name | created_at |
|---------|----------|-------|------------|-----------|------------|
| Int | Text | Text | Text | Text | timestamp |
My base SQL query might look like this:
baseQuery :: Query
baseQuery :: [sql| SELECT user_id, username, email, first_name, last_name, created_at FROM users |]
In the case of receiving url parameters I would want to be able to apply them to the WHERE clause, ORDER BY clause, etc.
What would be the best strategy to transform the following url:
arbitraryhost:/users?order_by_max=user_id&first_name=emg184&last_name=stackoverflow&limit=20
which would result in the following parameters list:
let params = [("order_by_max","user_id"), ("first_name","emg184"), ("last_name","stackoverflow"), ("limit", "20")]
How would i generate the follwing query:
"SELECT user_id, username, email, first_name, last_name, created_at
FROM users
WHERE first_name = ? AND last_name = ?
ORDER BY user_id
LIMIT ?"
("emg184", "stackoverflow", 20)
(I really like the way that the query builder knexjs works which allows for ad hoc fragments of queries to be generated and applied as a higher order function to some base query http://knexjs.org/)
Im wondering what a strategy or implementation of this might be as I have not been successful in building anything that I find to be very fitting for this.

Show first entry by timestamp of each event group

we collect custom events in application insights for each message a user sends to a chatbot. The event is called user_message.
We use a custom dimension field customDimensions.conversationid to know which message is related to which conversation.
I want to see the first message of each conversation so basically the "oldest" timestamp of each event based on the conversation id.
I tried to work with arg_max but I didn't figure out how it works.
customEvents
| extend itemType = iif(itemType == 'customEvent',itemType,"")
| where (itemType == 'customEvent')
| where name == 'User_Message'
i was able to show all user messages ordert by the conversationID however it shows me multiple lines and i only need the first message by conversation.
Datamodel:
timestamp [UTC] 2019-04-05T13:24:10.359Z
name User_Message
itemType customEvent
customDimensions
confidence N/A
conversationId BNu0SqC5RfA1S0lZmdxxxxx
intent N/A
userMessage user text
operation_Name POST /api/messages
operation_Id xxxxxxxa5d422eadebfebb2
operation_ParentId xxxxx545a5d422eadebfebb2.99811380_13.f033f887_
application_Version 1.0.0
client_Type PC
client_OS Windows_NT 10.0.14393
client_IP 0.0.0.0
client_City Amsterdam
client_StateOrProvince North Holland
client_CountryOrRegion Netherlands
cloud_RoleName Web
cloud_RoleInstance XXXXXXXFF74D594
appId ccccccc-8b24-41bb-a02a-1cb101da84e5
appName bot-XXXXX
iKey XXXXXX
sdkVersion node:XX
itemId XXXXXXXX-57a6-11e9-a5a7-ebc91e7cf64e
itemCount 1
SOLUION
customEvents
| extend itemType = iif(itemType == 'customEvent',itemType,"")
| where (itemType == 'customEvent')
| where (name=='User_Message')
| summarize list=makeset(customDimensions.userMessage) by
tostring(customDimensions.conversationId)
| mv-expand firstMessage=list[0]
Update:
customEvents
| where name == "User_Message"
| summarize timestamp=min(timestamp) by myconid=tostring(customDimensions.[conversationID])
| join kind= inner (
customEvents
| where name == "User_Message"
| extend myconid = tostring(customDimensions.[conversationID])
) on myconid,timestamp
You can use inner join to do that.
I don't have your data, so in your case, the code looks like below(maybe you need to make a little changes):
customEvents
| summarize timestamp=min(timestamp) by conversationID
| join kind= inner (
customEvents
) on conversationID,timestamp
| project-away conversationID1,timestamp1
Please let me know if you have more issues.

Resources