Inside my database model, I've got a json field which has the following structure:
json_field: {"data"=>{"key_1"=>"value1", "key_2"=>"value"} }
Trying to query this using select:
Model.select(:id, "json_field -> 'data'")
Model.select(:id, "json_field -> 'data' as data")
yields the array of objects, but without the json field selected.
#<ActiveRecord::Relation [#<Model id: 1, Model id: 2 ...>]
Thanks for any help.
This:
#<ActiveRecord::Relation [#<Model id: 1, Model id: 2 ...>]
is the result of calling inspect on the query and inspect will only display columns that the model knows about it. The model will query the table for the columns during startup so it will only know about columns that are actually in the table.
ActiveRecord creates column accessor methods on the fly using method_missing so it can create methods things in a query that aren't columns in the actual table.
So your data is there, you just have to ask for it by name, for example:
Model.select(:id, "json_field -> 'data' as data").map(&:data)
will give you the data values.
Related
I am trying to use the JSON array to create a quasar table but I am not able to link the array data with the table data.
I have stored the data from my database into an array called "scanResults" and the result is as shown:
console.log(scanResults);
Results of scanResults
Among the three arrays (Items, Count, and ScannedCount), I only want the data from Items. Is there a way I could put the data from scanResults into tableData under data() in the section such that I will be able to display the data into the quasar table?
tableData: [
{
name: 'xxx',
frequency: 'xxx',
prescription: 'xxx',
time: 'xxx'
}
]
<q-table
title="Reminders"
no-data-label="You do not have any reminders yet!"
align="center"
:columns="columns"
:data="tableData"
row-key="name"
selection="single"
:selected.sync="selected"
/>
If I am reading your scanResults correctly, you can set
tableData = scanResults.0[1]
to put the contents of the second place (the data) of the first array ("0") into tableData.
Did you define the columns array? The bindings must include both arrays so that QTable knows which data to put in which column. See the script tab of the "basic" section at https://quasar.dev/vue-components/table .
Let's take a simple schema with two tables, one that describes an simple entity item (id, name)
id | name
------------
1 | foo
2 | bar
and another, lets call it collection, that references to an item, but inside a JSON Object in something like
{
items: [
{
id: 1,
quantity: 2
}
]
}
I'm looking for a way to eventually enrich this field (kind of like populate in Mongo) in the collection with the item element referenced, to retrieve something like
{
...
items: [
{
item: {
id: 1,
name: foo
},
quantity: 2
}
]
...
}
If you have a solution with PostgreSQL, I take it as well.
If I understood correctly, your requirement is to convert an Input JSON data into MySQL table so that you can work with JSON but leverage the power of SQL.
Mysql8 recently released JSONTABLE function. By using this function, you can store your JSON in the table directly and then query it like any other SQL query.
It should serve your immediate case, but this means that your table schema will have a JSON column instead of traditional MySQL columns. You will need to check if it serves your purpose.
This is a good tutorial for the same.
I've been trying to use dynamic columns with an instance of MariaDB v10.1.12.
First, I send the following query:
INSERT INTO savedDisplays (user, name, body, dataSource, params) VALUES ('Marty', 'Hey', 'Hoy', 'temp', COLUMN_CREATE('type', 'tab', 'col0', 'champions', 'col1', 'averageResults'));
Where params' type was defined as a blob, just like the documentation suggests.
The query is accepted, the table updated. If I COLUMN_CHECK the results, it tells me it's fine.
But when I try to select:
"SELECT COLUMN_JSON(params) AS params FROM savedDisplays;
I get a {type: "Buffer", data: Array} containing binary returned to me, instead of the {"type":"tab", "col0":"champions", "col1":"averageResults"} I expect.
EDIT: I can use COLUMN_GET just fine, but I need every column inside the params field, and I need to check the type property first to know what kind of and how many columns there are in the JSON / params field. I could probably make it work still, but that would require multiple queries, as opposed to only one.
Any ideas?
Try:
SELECT CONVERT(COLUMN_JSON(params) USING utf8) AS params FROM savedDisplays
In MariaDB 10 this works at every table:
SELECT CONVERT(COLUMN_JSON(COLUMN_CREATE('t', text, 'v', value)) USING utf8)
as json FROM test WHERE 1 AND value LIKE '%12345%' LIMIT 10;
output in node.js
[ TextRow { json: '{"t":"test text","v":"0.5339044212345805"}' } ]
I am saving a list of followed users to the db and then trying to get the records where the current user is a part of that list but keep getting this exception.
SQLite3::SQLException: no such column: parameters.user: SELECT "activities".* FROM "activities" WHERE "parameters"."user" = 3
This is a record in the db
=> #<PublicActivity::Activity id: 107, trackable_id: 16, trackable_type: "Shout", owner_id: 1, owner_type: "User", key: "shout.shout", parameters: {:user=>[3]}, recipient_id: nil, recipient_type: nil, created_at: "2015-10-20 21:44:41", updated_at: "2015-10-20 21:44:41", read: false>
These are the queries I've tried that give me this. current_user.id = 3
PublicActivity::Activity.where({'parameters.user' => current_user.id})
PublicActivity::Activity.where(parameters: {user: current_user.id})
So. How do I get the records where the current user is a part of that list of users? Also, would the I be able to use the same query in Mysql?
Might seem like a silly question, but is the parameters column defined as a serialized column in the model? With adapters like MySQL and (I believe) SQLite you can't query serialized fields. So If it's something that you'd like to query, you need to save it separately from the serialized field.
That being said, with PostgreSQL and their rails adapter, you can query serialized fields.
You should check out this SO question and this anser
I'm using Postgrex in Elixir, and when it returns query results, it returns them in the following struct format:
%{columns: ["id", "email", "name"], command: :select, num_rows: 2, rows: [{1, "me#me.com", "Bobbly Long"}, {6, "email#tts.me", "Woll Smoth"}]}
It should be noted I am using Postgrex directly WITHOUT Ecto.
The columns (table headers) are returned as a collection, but the results (rows) are returned as a list of tuples. (which seems odd, as they could get very large).
I'm trying to find the best way to programmatically create JSON objects for each result in which the JSON key is the column title and the JSON value the corresponding value from the tuple.
I've tried creating maps from both, merging and then serialising to JSON objects but it seems there should be an easier/better way of doing this.
Has anyone dealt with this before? What is the best way of creating a JSON object from a separate collection and tuple?
Something like this should work:
result = Postgrex.query!(...)
Enum.map(result.rows, fn row ->
Enum.zip(result.columns, Tuple.to_list(row))
|> Enum.into(%{})
|> JSON.encode
end)
This will result in a list of json objects where each row in the resultset is a json object.