Group by query of Eloquent in laravel - database

I need a query which group by hour then return data.i have a column in database with name time and the value in time column is like 13:12:43.so how can group by hour.And i need the result with order by hour.I'm trying the given query but this query return sum of all units.But i need sum of units on the base of hour like [{ hour:1,unit:0.2232},{ hour:2,unit:0.3232},..so on]
$response = PowerConsumption::groupBY('time')
->selectRaw('round(sum(unit),4) as yAxis')
->where(['device_id' => 2])
->where('date',Carbon::now()->ToDateString)
->orderBy('time')->get();

from you controller :
$response = PowerConsumption::selectRaw('HOUR(time) as hour')
->where(['device_id' => 2])
->where('date',Carbon::now()->ToDateString)
->orderBy('time')->get()->groupBy('hour');
$results = [];
foreach ($response as $hour => $value) {
$results[] = ['hour'=> $hour, 'unit' => round($value->sum('unit'), 4)]
}
you can just do the results foreach in your view if you are not using ajax

Related

foreach by quantity in laravel

I develop a ticketing system which user have to choose the quantity of ticket category. I want to save the record to database by the total of quantity. But it seems to be failed. I end up only save the record by category id. Here is the result when I try to return it.
and this is my code in controller.
public function ticket_checkout(Request $request)
{
$ctg_id = $request->cat_id;
$price = $request->price;
$name = $request->name;
$qty = $request->qty;
// return count($qty);
$data = [];
$i = 0;
foreach($qty as $item){
if($qty[$i] != 0){
$data[] = [
"ctg_id" => $ctg_id[$i],
"price" => $price[$i],
"qty" => $item,
];
}
$i++;
}
return $data;
Ticket_checkout::insert($data);
// return $qty;
return view('ticket.index', compact('data','qty'));
}
I wonder if I missing something here? I tried to do looping 'for' by quantity inside the 'foreach' but it seems not working too.

Is there any way to fix Illegal offset type error when i try to update the content of pivot table in laravel

I'm trying to update the data of pivot table (i want to change product in the order)
I have :
-product table:
id
name
product_price
created_at
updated_at
-order table:
id
status
user_id
created_at
updated_at
-order_products table:
order_id
product_id
product_price
count
created_at
updated_at
in Order model:
public function product(){
return $this->belongsToMany('App\Product')->withPivot('count');
}
in Prodect model:
public function order(){
return $this->belongsToMany('App\Order');
}
in controller:
public function EditOrder(Request $request , $id){
$order = Order::find($id);
$order->status = $request->status;
$order->user_id = $request->user_id;
$order->update();
$product_ids = $request->products;
$selectedItems = [];
foreach ( $product_ids as $key => $productId) {
$id1 = $key['product_id'];
$product = Product ::find($id);
$count = $key['count'];
$selectedItems[$productId] = ['product_id' => $id1 ];
$selectedItems[$productId] = ['count' => $count];
$selectedItems[$productId] = ['order_id' => $order->id];
$selectedItems[$productId] = ['price' => $product->product_price];
$order->product()->updateExistingPivot($selectedItems);
}
return response()->json([
'message' => 'Success'
],200);
i faced this error :
Illegal offset type in file C:\Users\Acer\Documents\GitHub\easyrest\app\Http\Controllers\ResturantController.php on line 80
I want to update product_id and count in order_products
updateExistingPivot() expects 2 params, the first being the id of the relationship you want to update, the second being the array of columns you wish to update. You're not passing an id, so it's trying to use your array as the id, which is why you're getting the error. Fix your logic:
foreach($product_ids as $key => $productId) {
$id1 = $key['product_id'];
$product = Product::find($id);
$count = $key['count'];
$selectedItems[$productId] = ['product_id' => $id1];
$selectedItems[$productId] = ['count' => $count];
// $selectedItems[$productId] = ['order_id' => $order->id]; // [1]
$selectedItems[$productId] = ['price' => $product->product_price];
$order->product()->updateExistingPivot($productId, $selectedItems[$productId]); // [2]
}
[1]: You can omit order_id; $order->product()->updateExistingPivot() already knows the order_id and you're not updating it, so it's redundant.
[2]: You don't want to pass the entire $selectedItems array, only the sub-array contained in $selectedItems[$productId]
By passing $productId as the first argument of updateExistingPivot(), Laravel knows what row you want to update, and will use the array keys in $selectedItems[$productId] to determine which columns to update to what. I don't know if this will actually update product_id, but if it doesn't, you may need to detach() then attach() the data instead:
foreach($product_ids as $key => $productId) {
$selectedItems[$id1] = ['count' => $count];
$selectedItems[$id1] = ['price' => $product->product_price];
$order->products()->detach($productId);
$order->products()->attach($id1, $selectedItems[$id1]);
}

How to combine two different tables into one in codeigniter?

In this code, I have two different tables i.e. skill_master and jobs_category. Now, I want to get these two different table data into one and also convert its data into JSON format using json_encode.
$this->db->select('category');
$this->db->from('jobs_category');
$this->db->order_by('category');
$query1 = $this->db->get();
$result1 = $query1->result_array();
$this->db->select('key_skills');
$this->db->from('skill_master');
$this->db->order_by('key_skills');
$query2 = $this->db->get();
$result2 =$query2->result_array();
$arr = array();
foreach($result1 as $row)
{
foreach($result2 as $rows)
{
$arr[] = $row['category'].','.$rows['skill_master'];
}
}
$json = json_encode($arr);
echo $json;
For example:
table1: skill_master
key_skills
==========
java
php
dot net
table2: jobs_category
category
========
IT Jobs
Air line Jobs
Hardware Jobs
Now, Here I have two tables here. Now, I want to combine these two tables and want data in JSON format like ["java", "PHP", "dot net", "IT Jobs", "Air Line Jobs", "Hardware Jobs"]. So, How can I do this? Please help me.
Thank You
$this->db->select('category');
$this->db->from('jobs_category');
$this->db->order_by('category');
$query_category= $this->db->get();
$result_category = $query_category->result_array();
$this->db->select('key_skills');
$this->db->from('skill_master');
$this->db->order_by('key_skills');
$query_skills = $this->db->get();
$result_skills =$query_skills->result_array();
If You get records from table jobs_category and skill_master like this
$result_category =
[
'0' => ['category' => 'IT Jobs'],
'1' => ['category' => 'Air line Jobs'],
'2' => ['category' => 'Hardware Jobs']
];
$result_skills =
[
'0' => ['skill_master' => 'java'],
'1' => ['skill_master' => 'php'],
'2' => ['skill_master' => 'dot net']
];
$final_arr = $final_category_arr = $final_skill_arr = [];
foreach($result_category as $category_row)
{
$final_category_arr[] = $category_row['category'];
}
foreach($result_skills as $skill_row)
{
$final_skill_arr[] = $skill_row['skill_master'];
}
$final_arr = array_merge($final_category_arr, $final_skill_arr);
$json = json_encode($final_arr);
echo $json;
Result will be like this
["IT Jobs","Air line Jobs","Hardware Jobs","java","php","dot net"]
renaming column while fetching and merging data should work. try following code
$this->db->select('category');
$this->db->from('jobs_category');
$this->db->order_by('category');
$query_category= $this->db->get();
$result_category = $query_category->result_array();
$this->db->select('key_skills as category');
$this->db->from('skill_master');
$this->db->order_by('key_skills');
$query_skills = $this->db->get();
$result_skills =$query_skills->result_array();
$result = array_merge($result_category,$result_skills);

SilverStripe 3.1 loop associative array

In SilverStripe 3.1 I have a function that loops through an array and outputs its contents.
The output it gives me is:
Layout: John
Strategy: John
Management: Martin
In this example John has more than one job.
I would like to group the jobs if a person has more than one job.
This is my desired Output:
Layout and Strategy: John
Management: Martin
//$InfoFieldArray = array('Layout' => 'John', 'Strategy' => 'John', 'Management' => 'Martin');
public function createInfoFields($InfoFieldArray){
$Info = ArrayList::create();
foreach($InfoFieldArray as $key => $value ){
$fields = new ArrayData(array('FieldName' => $key, 'Value' => $value));
$Info->push($fields);
}
return $Info;
}
How do I alter my function to achieve my desired output?
One possible solution to that is by restructuring the data before adding it to the ArrayList.
public function createInfoFields($InfoFieldArray)
{
$info = array();
foreach ($InfoFieldArray as $job => $person)
{
if (!isset($info[$person]))
{
$info[$person] = array();
}
$info[$person][] = $job;
}
$result = ArrayList::create();
foreach ($info as $person => $jobs)
{
$fields = new ArrayData(array('FieldName' => implode(' and ', $jobs), 'Value' => $person));
$result->push($fields);
}
return $result;
}
What I have done is go over the array of jobs and the person assigned and flipped it the other way around, so I have an array of people with a list of jobs. This allows me to then just call implode in PHP, joining the various jobs by the word and.
There are some potential drawbacks, if there are two people named "John", they will be treated as one as I am using the name as the array key.
Also, if there are three jobs for a person, it will list it like "Layout and Strategy and Management". To avoid that, we need to modify the second foreach loop in my code to something like this:
foreach ($info as $person => $jobs)
{
$jobString = null;
if (count($jobs) > 1)
{
$jobString = implode(', ', array_slice($jobs, 0, -1)) . ' and ' . array_pop($jobs);
}
else
{
$jobString = $jobs[0];
}
$fields = new ArrayData(array('FieldName' => $jobString, 'Value' => $person));
$result->push($fields);
}
When there is more than 1 job for a person, we want to implode (glue together) the array pieces for the $jobs array however we don't want the last element at this point. Once array is glued together, we append with with and along with the last item.

Cakephp save data and read MAX

I'm trying to save data in CakePHP in this way:
get max entry_id from table translations
(SELECT MAX(entry_id) as res FROM translations) + 1
save data into translations table
$translationData = array('entry_id' => $entry_id, 'language_id' => $key, 'text' => $item);
$translation = new Translation();
$translation->set($translationData);
$translation->save();
again get max entry_id
save next set of data
again get max entry_id
save next set of data
Please have a look at my code:
$this->request->data['Product']['name_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['name']);
$this->request->data['Product']['description_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['description']);
$this->request->data['Product']['seo_title_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_title']);
$this->request->data['Product']['seo_keywords_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_keywords']);
$this->request->data['Product']['seo_desc_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_desc']);
saveTranslations method:
public function saveTranslations($data) {
$entry_id = $this->getNextFreeId();
foreach($data as $key => $item) {
if($item != "") {
$this->create();
$temp['Translation']['entry_id'] = $entry_id;
$temp['Translation']['language_id'] = $key;
$temp['Translation']['text'] = $item;
$this->save($temp);
}
}
return $entry_id;
}
getNextFreeId method:
public function getNextFreeId() {
$result = $this->query("SELECT MAX(entry_id) as res FROM translations");
return $result[0][0]['res'] + 1;
}
I don't know why entry_id have all the time the same value.
After many hours of searching for solution I finally managed to solve the problem in very easy way - just add false parameter in query method:
$this->query("INSERT INTO translations(entry_id, language_id, text) VALUES($entry_id, $key, '$item')", false);
and
$result = $this->query("SELECT SQL_CACHE MAX(entry_id) as res FROM translations", false);

Resources