Fetching value in the json array in MySQL, Laravel - mysql

I have that kinda table and data :
Table Name : data
+------+-----------------+--------+----------+
| id | number | name | surname |
+------+-----------------+--------+----------+
| 1 | [1, 2, 3, 4, 5] | John | Doe |
| 2 | [1, 2, 4, 8] | James | Webb |
| 3 | [3, 4, 5] | Jenny | Test |
+------+-----------------+--------+----------+
For example, I want to fetch the rows in the number column with the value 3 :
+------+-----------------+--------+----------+
| id | number | name | surname |
+------+-----------------+--------+----------+
| 1 | [1, 2, 3, 4, 5] | John | Doe |
| 3 | [3, 4, 5] | Jenny | Test |
+------+-----------------+--------+----------+
I tried that with Laravel but didn't work. :
DB::table('data')
->whereRaw('FIND_IN_SET(?, number)', [3])
->get();
How can I solve that problem? Thanks for your answers.

You can use toJson(), to convert the collection to json object in Laravel.
$_data = DB::table('data')
->whereRaw('FIND_IN_SET(?, number)', [3])
->get()->toJson();
dd($_data);
Have a look at the [documentation] https://laravel.com/docs/9.x/responses#json-responses

Thanks for your answers. I found the answer to my question as follows :
I made the Array values as strings. Like that :
Table Name : data
+------+---------------------------+--------+----------+
| id | number | name | surname |
+------+---------------------------+--------+----------+
| 1 | ["1", "2", "3", "4", "5"] | John | Doe |
| 2 | ["1", "2", "4", "8"] | James | Webb |
| 3 | ["3", "4", "5"] | Jenny | Test |
+------+---------------------------+--------+----------+
And then I used to this codes. :
$_data = DB::table('data')
->where('number', 'LIKE', '%"' . "3" . '"%')
->get();
Also you can do with SQL commands. Like that :
SELECT *
FROM data
WHERE number LIKE '%"3"%';
Exactly like I want, it turned to me this :
+------+---------------------------+--------+----------+
| id | number | name | surname |
+------+---------------------------+--------+----------+
| 1 | ["1", "2", "3", "4", "5"] | John | Doe |
| 3 | ["3", "4", "5"] | Jenny | Test |
+------+---------------------------+--------+----------+

Related

Split SQL Table with fields containing JSON into multiple rows

I have a table t with 2 fields: one containing an id, and the other one containing a json.
My table looks like this:
| id | json |
|:---|:----------------------------------------------|
| 1 | {"tag1":45, "tag2": 3, "tag5": 10} |
| 2 | {"tag5":35, "tag6": 7, "tag8": 10, "tag10": 4}|
| 3 | {"tag2":10, "tag800": 6} |
I am trying to write a postgresql query to create a table that looks like the following but I am stuck:
| id | key | Value |
|:---|:--------|:------|
| 1 | tag1 | 45 |
| 1 | tag2 | 3 |
| 1 | tag5 | 10 |
| 2 | tag5 | 35 |
| 2 | tag6 | 7 |
| 2 | tag8 | 10 |
| 2 | tag10 | 4 |
| 3 | tag2 | 10 |
| 3 | tag800 | 6 |
Note that there are thousands of different keys in my data.
Any help would be much appreciated. Thanks!
Recreating your example with
CREATE TABLE test(id int, mydata jsonb);
insert into test values (1, '{"tag1":45, "tag2": 3, "tag5": 10}');
insert into test values (2, '{"tag5":35, "tag6": 7, "tag8": 10, "tag10": 4}');
insert into test values (3, '{"tag2":10, "tag800": 6} ');
You can achieve what you're looking for with the jsonb_each function
select id, key, value from test, jsonb_each(test.mydata)

Retrieve many to many relation with laravel eloquent

I'm trying to retrieve data from many to many relation grouped in one object for the duplicated date.
I have menu table and daily_mealz table and pivot table(menu_daily_mealz)
the problem is the daily_mealz contain duplicated date value in its date column but every raw contain different meal_id.
So, I need to retrieve one raw but contain all mealsIDs related to this date
I only retrieve with belongsTo relation and them for loop over the data to get the object I need.
Relations
public function dailyMeals(){
return $this->belongsToMany(DailyMeals::class, 'menu_daily_meals', 'menu_id', 'daily_meal_id');
}
public function menus(){
return $this->belongsToMany(Menu::class, 'menu_daily_meals', 'daily_meal_id', 'menu_id');
}
DataBase Structure
Menu table
+-----+----------------+
| id | name |
+-----+----------------+
| 1 | first menu |
| 2 | second menu |
+-----+----------------+
daily mealz table
+----+-------------+---------+-------+
| id | date | meal_id | stock |
+----+-------------+---------+-------+
| 1 | 2019-03-01 | 1 | 250 |
| | | | |
| 2 | 2019-03-01 | 2 | 100 |
| | | | |
| 3 | 2019-03-02 | 3 | 150 |
| | | | |
| 4 | 2019-03-02 | 4 | 70 |
| | | | |
| 5 | 2019-03-03 | 5 | 350 |
| | | | |
| 6 | 2019-03-03 | 6 | 180 |
+----+-------------+---------+-------+
Menu_daily_meals table
+----+---------+---------------+
| id | menu_id | daily_meal_id |
+----+---------+---------------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 1 | 4 |
| 5 | 1 | 5 |
| 6 | 1 | 6 |
| 7 | 2 | 3 |
| 8 | 2 | 5 |
| 9 | 2 | 6 |
+----+---------+---------------+
I need to retrieve object like that
{
"id": 1,
"name": "first menu",
"daily_meals": [
{
"id": 1,
"daily_date": "2019-03-01",
"meals" : [
{
"meal_id" : 1,
"stock" : 250
},
{
"meal_id" : 2,
"stock" : 100
},
]
},
{
"id": 2,
"daily_date": "2019-03-02",
"meals" : [
{
"meal_id" : 3,
"stock" : 150
},
{
"meal_id" : 4,
"stock" : 70
},
]
},
{
"id": 3,
"daily_date": "2019-03-03",
"meals" : [
{
"meal_id" : 5,
"stock" : 350
},
{
"meal_id" : 6,
"stock" : 180
},
]
}
]
}
Any Help, Please?
You should use load function to load external data to your model(use eager loading):
$menu=Menu::find(1);
$menu->load('dailyMeals','dailyMeals.meals');
Note : For hide pivot object in response add this code to your menu model:
protected $hidden = ['pivot'];
Note : You should have dailyMeals in your menu model and meals relation in your dailyMeals model
For more information You can Visit Laravel Document.

Extract key, value from columns field in Postgresql table

id | columns | timestamp | query_id | task_id
-------+----------------------------------------------+----------------------------+----------------------+---------------------------
1 | {"uid": "112", "name": "redis-server"} | 2018-07-18 18:45:39.045387 | 1 | 2
2 | {"uid": "0", "name": "celery"} | 2018-07-18 18:45:39.047671 | 1 | 2
3 | {"uid": "111", "name": "post"} | 2018-07-18 18:45:39.048218 | 1 | 2
4 | {"uid": "111", "name": "post"} | 2018-07-18 18:45:39.048732 | 1 | 2
Looking to extract normal values from json for UID & NAME through query syntax
You can use JSON operator ->>. ie:
select *, "columns"->>'uid' as uid, "columns"->>'name' as name
from myTable;

Replace subset of MySQL records

I have a MySQL database called ice_cream with three tables, users, flavors, and favorites. Each record in favorites has a reference to a user and a flavor, and a user is able to have multiple ice cream flavors.
I'm trying to write a transaction to completely replace a user's favorites with another set of favorites. For example, when the API accepts
PUT /user/100/favorites
{
"flavors": {
"2": { "stars": 2 },
"3": { "stars": 5, "comments": "Changed my life" },
"18": { "stars": 4, "comments": "👅 " },
"24": { "stars": 4 }
}
}
The favorites table should change from
| id | user_id | flavor_id | stars | comments |
| --- | ------- | --------- | ----- | ------------------ |
| 200 | 100 | 2 | 2 | Tastes OK |
| 201 | 100 | 4 | 3 | |
| 202 | 100 | 5 | 3 | |
To
| id | user_id | flavor_id | stars | comments |
| --- | ------- | --------- | ----- | ------------------ |
| 200 | 100 | 2 | 2 | |
| 201 | 100 | 3 | 5 | Changed my life |
| 203 | 100 | 18 | 4 | 👅 |
| 204 | 100 | 24 | 4 | |
What's the most efficient set of statements to accomplish this?
Points to consider:
I'm not concerned with keeping primary ids consistent.
The users are really into the small-batch craft ice cream scene and will usually replace about 5000 records each transaction.
in this case the most efficient set of statements is delete and insert
delete from flavors
where user_id =100;
and a loop server side for insert the new values or a batch insert with all the values in repated values rows
insert into flavors ( user_id, flavor_id, stars , comments )
values ( 100,2 ,2 null),
(100, 3, 5 , 'Changed my life'),
(100 ,18,4 , 👅 ),
(100 , 24 ,4 , null)

How to use MySQL select statement to generate rows for each entry in a JSON list?

I have a JSON column in a MySQL table.
A column contains a list of dictionaries. I would like for each item in the list to get it's own row, with the row ID. See the example below for better understanding.
Example:
mysql> select id, geography from region;
+------|-------------------------------------------------------------------------------------------------------------+
| id | geography |
+------|-------------------------------------------------------------------------------------------------------------+
| 1 | [{"state": "SC", "county": "BERKELEY"}}] |
| 2 | [{"county": "Placer", "state": "CA"}, {"county": "Sacramento", "state": "CA"}] |
| 3 | [{"county": "Jeff", "state": "MO"},{"county": "Charles", "state": "MO"},{"county": "Louis", "state": "MO"}] |
+------|-------------------------------------------------------------------------------------------------------------+
Desired output:
+------|--------------|-------------+
| id | county | state |
+------|--------------|-------------|
| 1 | BERKELEY | SC |
| 2 | Placer | CA |
| 2 | Sacramento | CA |
| 3 | Jeff | MO |
| 3 | Charles | MO |
| 3 | Louis | MO |
+------|--------------|-------------+
It seems to be a bad idea to do that, but sometimes you have to, I guess.
3 options come to mind:
If you're using MySQL >=5.7.8, use internal JSON-related functions
JSON UDF for MySQL
Use common_schema
Your best shot would probably be 3rd option. You should lookup common_schema.extract_json_value().