how to sum column value using group by collection in magento(USING MAGENTO STANDARD) - magento

my table is like this and my collection is
$testmodel=Mage::getModel(test/p1)->getCollection();
my database table is below.
id cat_id rate p_id
1 1 4 1
2 1 2 1
3 1 3 2
4 2 5 3
5 2 3 1
and i want output like this in magento using collection
cat_id rate count_category
1 9 3
2 8 2

i found my PROBLEM correct code is below
$testmodel = Mage::getModel('test/p1')
->getCollection()
->addFieldToSelect('rate')
->addFieldToSelect('cat_id');
$testmodel ->getSelect()
->columns('SUM(rate) as total,COUNT(*) AS countCategory')
->group('cat_id');

if you use mysql4 as this model resource class then go to
Model/Mysql4/P1/Collection.php
here you need to add function
public function addGroupByCatId(){
$subSelect = clone $this->getSelect();
$CountsubSelect = clone $this->getSelect();
$subSelect->reset()
->from(array('rev' => 'youtable', 'SUM( rev.rate)')
->where('main_table.cat_id = rev.cat_id');
$CountsubSelect->reset()
->from(array('countrev' => 'youtable'),'COUNT(countrev.cat_id)')
->where('main_table.cat_id = countrev.cat_id');
$this->getSelect()
->join(
array('r' => 'youtable'),
'main_table.id = r.id',
array(
'review_sum' => new Zend_Db_Expr(sprintf('(%s)', $subSelect)),
'count_category' => new Zend_Db_Expr(sprintf('(%s)', $CountsubSelect)),
))
->group('main_table.cat_id');
return $this;
}
OR: Resouce as resource model then goto
if you use mysql4 as this model resource class then go to
Model/Resource/P1/Collection.php
here you need to add function
public function addGroupByCatId(){
$subSelect = clone $this->getSelect();
$CountsubSelect = clone $this->getSelect();
$subSelect->reset()
->from(array('rev' => 'youtable', 'SUM( rev.rate)')
->where('main_table.cat_id = rev.cat_id');
$CountsubSelect->reset()
->from(array('countrev' => 'youtable'),'COUNT(countrev.cat_id)')
->where('main_table.cat_id = countrev.cat_id');
$this->getSelect()
->join(
array('r' => 'youtable'),
'main_table.id = r.id',
array(
'review_sum' => new Zend_Db_Expr(sprintf('(%s)', $subSelect)),
'count_category' => new Zend_Db_Expr(sprintf('(%s)', $CountsubSelect)),
))
->group('main_table.cat_id');
return $this;
}
and final you get
$testmodel=Mage::getModel(test/p1)->getCollection();
$testmodel->addGroupByCatId();

Related

How to add array values to another array

I have two sets of array A and B, array A and B on submission is supposed to enter a database table.
A(result)
array:2 [
0 => 7
1 => 8
]
B
array:3 [
"student_test_id" => 8
"question_id" => 4
"test_id" => 3
]
EXPECTED RESULT
On submit, i want the values of Array A and B to enter this table like this
id| student_test_id | test_id | question_id |result
1 | 8 | 3 | 4 | 7
2 | 8 | 3 | 4 | 8
WHAT I HAVE TRIED
$result = $request->result;
$array_conv = array(
"student_test_id"=>$request->student_test_id,
"question_id"=>$request->question_id,
"test_id"=>$request->test_id,
);
foreach($request->result as $result){
$test_log = new StudentTestLog();
$test_log->student_test_id = $array_conv["student_test_id"];
$test_log->question_id = $array_conv["question_id"];
$test_log->test_id = $array_conv["test_id"];
$test_log->result = $result['id'];
$test_log->save();
if($test_log->save()){
return response()->json('Submited', 200);
}else{
return response()->json('Error Submitting', 400);
}
}
Please assist Thank you
When returning response from foreach except first all other iterations of loop are omitted as return ends method execution. You should move return statements outside the loop. Try something like this:
$array_conv = array(
"student_test_id"=>$request->student_test_id,
"question_id"=>$request->question_id,
"test_id"=>$request->test_id,
);
$data_to_persist = [];
foreach($request->result as $result){
array_push( $data_to_persist, [
'student_test_id' => $array_conv["student_test_id"],
'question_id' => $array_conv["question_id"],
'test_id' => $array_conv["test_id"],
'result' => $result['id']
]);
}
$saved = StudentTestLog::insert( $data_to_persist );
if($saved){
return response()->json('Submited', 200);
}else{
return response()->json('Error Submitting', 400);
}

Laravel Pluck 3 arrays

can I pluck the 3 arrays like these because only two are shown?
$data = Receipt::select(DB::raw("DATE(created_on) as date"), DB::raw("sum(case when type = 'Receipt' then 1 else 0 end) AS cnt_receipt"), DB::raw("sum(case when type = 'Invoice' then 1 else 0 end) AS cnt_invoice"))
->groupBy('date')
->pluck('cnt_receipt', 'cnt_invoice', 'date')->all();
If not, how can I able show those 3 arrays?
I want the output something like this
date cnt_receipt cnt_invoice
2021-01-01 5 6
2021-01-02 8 5
2021-01-03 10 9
2021-01-04 11 9
I need to get those data as arrays because the chart js code need array_keys and array_values
$chart= new Chart;
$chart->labels = (array_keys($data));
$chart->r_dataset = (array_values($data));
$chart->i_dataset = (array_values($data));
Chart Class
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Chart extends Model
{
//
}
What you need to use is reduce here, a bit of a hacky way, but it will work.
$data = Receipt::select(DB::raw("DATE(created_on) as date, sum(case when type = 'Receipt' then 1 else 0 end) AS cnt_receipt, sum(case when type = 'Invoice' then 1 else 0 end) AS cnt_invoice"))
->groupBy('date')->all();
Then;
$chartInitial = new Chart();
$chartInitial->labels = [];
$chartInitial->r_dataset = [];
$chartInitial->i_dataset = [];
$chart = $data->reduce(function($obj, $row){
$obj->labels[] = $row->date;
$obj->r_dataset[] = $row->cnt_receipt;
$obj->i_dataset[] = $row->cnt_invoice;
return $obj;
}, $chartInitial);
It'll push all the row data into their respective arrays in that Chart object.

Echo from foreach

i have model that return
return array(
'senin'=> $senin->result(),
'selasa'=> $selasa->result(),
'rabu'=> $rabu->result()
);
and controller
$data['ot'] = $this->genbamodel->getOt();
in my view, i use 'foreach $ot as key' and when i tried to print_r($key) the result like this
Array()
Array ( [0] => stdClass Object ( [id_genba] => 1 [hari] => Tuesday [shift1] => 2 [shift2] => 0 ))
Array ( [0] => stdClass Object ( [id_genba] => 1 [hari] => Wednesday [shift1] => 1 [shift2] => 2 ))
how to get just shift1 = 2 and shift2 = 0 (from second array / hari=>Tuesday ??
Thankyou
I don't think you need the foreach loop to access those values. To get just the second record, you can do the below.
$ot['selasa'][0]->shift1
$ot['selasa'][0]->shift2
$ot['selasa'][0]->hari

how to make multi dimension array from sql return rows in codeigniter

how to make multi dimension array from sql return rows in codeigniter.
return values from model holding all values in $res.
$res = $this->user_model->get_room_book_join(['rooms.hotel_id' => 1]);
if ($res) {
echo '<pre>';
print_r($res);
}
I getting this type of array.this type can not helping me.
Array( [0] => Array
(
[room_id] => 1
[room_no] => 101
[room_desc] => Double Bed Deluxe Non Air Conditioned
[status] => available
[category_id] => 1
[hotel_id] => 1
[tariff_type] => normal
[room_rate] => 1000
[persons] => 0
[date_start] => 0000-00-00
[date_end] => 0000-00-00
[overview_id] => 1
[rom_id] => 1
[hot_id] => 1
[cus_id] => 2
[bok_id] => 2
[dates] => 2017-04-12
)
[1] => Array
(
[room_id] => 2
[room_no] => 101
[room_desc] => Double Bed Deluxe Non Air Conditioned
[status] => available
[category_id] => 1
[hotel_id] => 1
[tariff_type] => normal
[room_rate] => 1000
[persons] => 0
[date_start] => 0000-00-00
[date_end] => 0000-00-00
[overview_id] => 1
[rom_id] => 1
[hot_id] => 1
[cus_id] => 2
[bok_id] => 2
[dates] => 2017-04-13
)
)
Actually I want this type of array.how can i make it.please help advance thanks.
array(
[0]=>array(
[room_id]=>1
[dates]=>array(
[0]=>2014-04-12
[1]=>2014-04-13
)
)
[1]=>array(
[room_id]=>2
[dates]=>array(
[0]=>2014-04-12
[1]=>2014-04-13
)
)
)
Hi, you can try this code, this may help you
$query = $this->db->get();
$result = $query->result_array();
$main_array=array();
$actual_array=array();
foreach($result as $res){
$main_array['room_id']=$res['room_id'];
$main_array['dates']=array($res['date_start'],$res['date_end']);
$actual_array[]=$main_array;
}
//echo ""; print_r($actual_array);
return $actual_array;
try this
// after if ($res) {
for ($i=0; $i < count($res); $i++) {
$res[$i] = array(
'room_id' => $res[$i]['room_id'],
'dates' => array($res[$i]['date_start'],$res[$i]['date_end'])
);
}

get distinct record from 3 tables using join in codeigniter

i have three tables
cases,clients,attendance
in cases
id start_date end_date client_id status
1 2012-12-30 2013-01-30 1 new starts
2 2012-12-31 2013-01-31 2 probation
in clients
id Name dob gender status
1 TOM 1987-01-30 M A
2 JERRY 1985-01-31 F D
in attendance
id client_id date status
1 1 2013-01-30 A
2 1 2013-01-31 P
i need result like this
case_id case_start_date case_end_date client_id Name
att_date atte_status
1 2012-12-30 2013-01-30 1 TOM
2013-01-30,2013-01-31 A,P
is this possible? i'm a self learner and i don't have good idea in join query please any body help me....
try this..
$this->db->select('ca.*,ci.Name,a.date,a.status');
$this->db->from('cases'.' ca');
$this->db->join('clients'.' ci','ca.client_id=ci.id','left');
$this->db->join('attendance'.' a','a.client_id=ci.id','left');
return $this->db->get();
go through the user guide if u want to read more about join and active records...
Here's a very simple example to get you started with any number of join common fun for all
Construcor Code
Construct $joins as array:
$joins = array(
array(
'table' => 'table2',
'condition' => 'table2.id = table1.id',
'jointype' => 'LEFT'
),
);
Example function handling joins as an array:
public function get_joins($table, $columns, $joins)
{
$this->db->select($columns)->from($table);
if (is_array($joins) && count($joins) > 0)
{
foreach($joins as $k => $v)
{
$this->db->join($v['table'], $v['condition'], $v['jointype']);
}
}
return $this->db->get()->result_array();
}

Resources