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.
Related
I have two tables as follows that joined by budget_id.
finance_budget table
+-----------+--------+------------+-----------------+---------------+
| budget_id | amount | date | transfer_status | budget_status |
+-----------+--------+------------+-----------------+---------------+
| 1 | 135000 | 2019-10-01 | Pending | issue |
| 2 | 25000 | 2019-10-02 | Pending | issue |
| 3 | 234000 | 2019-10-03 | Pending | issue |
| 4 | 175000 | 2019-10-03 | Pending | issue |
+-----------+--------+------------+-----------------+---------------+
finance_budget_issue table
+----+-----------+-----------+--------+-----------------+---------------+
| id | budget_id | office_id | amount | transfer_status | budget_status |
+----+-----------+-----------+--------+-----------------+---------------+
| 1 | 1 | 100 | 135000 | Pending | issue |
| 2 | 2 | 101 | 12500 | Pending | issue |
| 3 | 2 | 102 | 12500 | Pending | issue |
| 4 | 3 | 100 | 100000 | Pending | issue |
| 5 | 3 | 105 | 75000 | Pending | issue |
| 6 | 3 | 104 | 59000 | Pending | issue |
| 7 | 4 | 102 | 125000 | Pending | issue |
| 8 | 4 | 110 | 50000 | Pending | issue |
+----+-----------+-----------+--------+-----------------+---------------+
I tried to change the "transfer_status" of above two tables from "Pending" to "Approved" using my model
Controller
public function approveIssues($id){
$this->checkPermissions('index', 'pendingIssues');
if(empty($id)){
redirect('budget/pendingIssue');
}
if($this->Budget_model->approveIssues($id)){
$this->session->set_flashdata('message', 'Allocation Approved successfully ..!!');
redirect('budget/pendingIssue');
}else{
$this->session->set_flashdata('error', 'Error ...!!!');
redirect('budget/pendingIssue');
}
}
Model
function approveIssues($id)
{
$this->db->update('finance_budget_issue', array('transfer_status'=>'Approved'), array('id' => $id));
$this->db->update('finance_budget', array('transfer_status'=>'Approved'), array('budget_id' => $id));
if ($this->db->affected_rows()) {
$activity=FZ_Controller::activity('approve','finance_budget_issues',$id,NULL);
$this->db->insert('finance_user_activity',$activity);
return true;
}
return false;
}
When I press the Approved button in my view the system shows "Error". If I remove the line, $this->db->update('finance_budget', array('transfer_status'=>'Approved'), array('budget_id' => $id));
in my model the operation is executing successfully and shows the "Allocation Approved successfully ..!!" Message.
Desired Output
I also need the transfer_status of finance_budget table should be into "Approved".
You can try this Model Code
function approveIssues($id) {
$this->db->set('finance_budget.transfer_status','Approved');
$this->db->set('finance_budget_issue.transfer_status','Approved');
$this->db->where('finance_budget.budget_id', $id);
$this->db->where('finance_budget_issue.id', $id);
$this->db->update('finance_budget JOIN finance_budget_issue ON finance_budget.budget_id = finance_budget_issue.id');
if ($this->db->affected_rows()) {
$activity=FZ_Controller::activity('approve','finance_budget_issues',$id,NULL);
$this->db->insert('finance_user_activity',$activity);
return true;
}
return false;
}
i think it's very helpful for you.
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)
I need a sum of unit for that devices 1,2 on the base of date but i'm trying with my query but result is not right.And i don't when having function is used.so please help me.My query,schema sample and expected result is given below
Database data
|--------------------------------------
|device_id | unit | date
|--------------------------------------
| 1 | 2 | 2016-07-01
---------------------------------------
| 1 | 3 | 2016-07-02
--------------------------------------
| 2 | 1 | 2016-07-02
--------------------------------------
| 2 | 4 | 2016-07-10
--------------------------------------
| 1 | 3 | 2016-07-10
-------------------------------------
| 2 | 1 | 2016-07-21
--------------------------------------
| 2 | 2 | 2016-07-23
--------------------------------------
| 1 | 3 | 2016-07-25
--------------------------------------
| 2 | 2 | 2016-07-27
--------------------------------------
| 1 | 3 | 2016-07-27
My query
$startMonth=Carbon::today()->startOfMonth()->toDateString();
$now=Carbon::today()->toDateString();
$consumption= PowerConsumption::groupBY(['date'])
->selectRaw('sum(unit) as yAxis,date')
->whereIn('device_id',[1,2])
->whereBetween('date',[$startMonth,$now])->get();
And Expected Result
[
{
yAxis:2,
date:2016-07-01
},
{
yAxis:4, //3+1
date:2016-07-02
},
{
yAxis:7, //4+3
date:2016-07-10
},
{
yAxis:1,
date:2016-07-21
},
{
yAxis:2,
date:2016-07-23
},
{
yAxis:3,
date:2016-07-25
},
{
yAxis:5, //2+3
date:2016-07-27
}
]
Please help me by modify my query and query return above expected result
I need to give my Angular JS application a JSON which represents Parent-Child Relationship of to tables.
Parent(Group):
+----+---------------+-------------+----------------+
| id | external_code | supplier_id | notes |
+----+---------------+-------------+----------------+
| 19 | asdfas | 3 | sadfa |
| 23 | 454 | 1 | groupa1 |
| 24 | sadfas221 | 2 | asfd |
| 25 | dsafas | 2 | NULL |
| 21 | 4545 | 1 | asdfasf |
+----+---------------+-------------+----------------+
Child(GroupItems):
+----------+---------+--------+
| group_id | item_id | status |
+----------+---------+--------+
| 19 | 1 | 0 |
| 19 | 2 | 0 |
| 19 | 3 | 0 |
| 25 | 2 | 0 |
+----------+---------+--------+
My desired JSON should look like this:
[
{"groupId":"19",
"notes":"sadfa",
"extenalCode":"asdfas",
"supplierId":"2",
"itemCount":3
"items":[{"itemId": "1","status":"Created", "weight":23},
{"itemId": "2","status":"Created", "weight":23}
{"itemId": "3","status":"Created", "weight":23}
]
},
....
]
The question is how to insert and bind child items with parent representing JSON semantics using MySQL and PlayFramework2.0(Slick)?
roughly something like this:
val items =
GroupItems.join(Items).on(_.itemId === _.id).run // <- query fetching items with group_ids
.groupBy(_._1.groupId).toMap
.mapValues(_._2) // <- mapping Map values to only items
// render groups to json and add a field items with the items (I may be wrong about Play's json api names)
val json = Group.run.map(g => Json.toJson(g) ++ JsObject("items" -> Json.toJson(items(g.id))))
I am currently trying to process a large block of simulation data (~2Gb worth). The data is in a table which looks like:
Table: Simulation Data
+-------+--------+----------+-------+
| id | run_id | timestep | value |
+-------+--------+----------+-------+
| 1 | 1 | 1 | 0.00 |
| 2 | 1 | 2 | 0.003 |
| : | : | : | : |
| 9543 | 1 | 9543 | 0.23 |
| 9544 | 2 | 1 | 0.00 |
| : | : | : | : |
+-------+--------+----------+-------+
So for each run (identified by a run_id) there are a number of time steps with corresponding data (in the case of run_id 1, there were 9543 time steps).
Durring a simulation run, there are events which take place. These event time steps are recorded in another table:
Table: Simulation Events
+-------+--------+----------+
| id | run_id | timestep |
+-------+--------+----------+
| 1 | 1 | 152 |
| 2 | 1 | 193 |
| 3 | 1 | 382 |
| : | : | : |
| 143 | 1 | 9382 |
| 144 | 2 | 137 |
| : | : | : |
+-------+--------+----------+
So for this set of data, with run_id 1, there were events at time step 152, 193, 382, ... 9382. run_id 2 has its first event at time step 137, etc. I am interested in what happens in the 3-timesteps before, the time step of, and the 3-timesteps after each event for each run_id. I would like to put together a query that returns something that looks like:
+--------+----------------+----------+-------+
| run_id | event_timestep | delta_ts | value |
+--------+----------------+----------+-------+
| 1 | 152 | -3 | 0.053 |
| 1 | 152 | -2 | 0.042 |
| 1 | 152 | -1 | 0.031 |
| 1 | 152 | 0 | 0.003 |
| 1 | 152 | 1 | 0.532 |
| 1 | 152 | 2 | 0.736 |
| 1 | 152 | 3 | 1.138 |
| 1 | 193 | -3 | 0.049 |
| : | : | : | : |
| 1 | 9382 | -3 | 0.068 |
| : | : | : | : |
| 1 | 9382 | 3 | 1.523 |
+--------+----------------+----------+-------+
Where the first row, with delta_ts = -3 would be the value from timestep 149, -2 would be from timestep 150, -1 from timestep 151, etc. Any thoughts on putting together a query that would do this?
There's two differing points of view on this:
You can use blank joins (cartesian products) select ... from table t1, table t2 where ..., but you have to figure out a condition that links two rows if and only if they're "related". Also keep in mind that pairs are commutative in your example, so add a condition like t1.id<t2.id -- also excludes self-joins.
or you can use a cursor in a stored procedure, and store values for the previous n steps, and correlate them manually. This is slower, uses more memory, but it's easier to write.