Laravel Pluck 3 arrays - laravel

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.

Related

Loop through collection in laravel and get specific data from the collection

I'm trying to go through a collection and I need to get a list of products according to certain keys. but I get the following error when I print the list with dd:
"array_key_exists(): The first argument should be either a string or an integer"
this is my function
public function reemplazaCostoZona($zona, $destino, $especie, $costo, $transporCollect){
$productos = $transporCollect->where([['zona',$zona],['destino', $destino],['especie',$especie]])
->pluck('producto');
dd($productos );
}
Collection:
I need to obtain the list of products for destination zone and species, That is to say that for my example of collection, for zone 1 destination 5 specie 1 I would have in my list product 1 and there may be more.
function where Im obtain collection:
public function storeTranspor3($request){
DB::table('transpor')->truncate();
$var = DB::select("select flu.zona, flu.destino, flu.producto, pro.especie, sup.codigo, dtr.cod_fundo, sup.sup_ha, dtr.dist_pavimento, dtr.dist_no_pavimento, dtr.peaje
from flujos flu
left join super sup on (sup.zona = flu.zona)
left join d_transporte dtr on (dtr.cod_fundo = (sup.codigo / 1000000) and dtr.destino = flu.destino)
left join productos pro on (pro.producto = flu.producto)
left join especies esp on (esp.especie = pro.especie)
order by flu.zona, dtr.cod_fundo, flu.producto, flu.destino, sup.codigo");
$tansporCollect = collect();
$tansporCollectsinCosto = collect();
foreach ($var as $f) {
if($f->codigo != null){
if($f->especie == 1){
$a = 0.177548*$f->dist_no_pavimento;
$b = 0.0746*$f->dist_pavimento;
$c = 0.0333*$f->peaje;
$costoFundo = ($a + $b + 1.1191 + 0.399 + $c)*$f->sup_ha;
}
else{
$a = 0.1652*$f->dist_no_pavimento;
$b = 0.0694*$f->dist_pavimento;
$c = 0.0357*$f->peaje;
$costoFundo = ($a + $b + 1.0421 + 0.599 + $c)*$f->sup_ha;
}
$tansporC =[
'zona' => $f->zona,
'destino' => $f->destino,
'producto' => $f->producto,
'especie' => $f->especie,
'costo' => $costoFundo
];
$tansporCollect->push($tansporC);
$tansporsinCosto = [
'zona' => $f->zona,
'destino' => $f->destino,
'producto' => $f->producto,
'especie' => $f->especie,
];
$tansporCollectsinCosto->push($tansporsinCosto);
}
}
$zonas = $tansporCollect->pluck('zona')->unique();
$destinos = $tansporCollect->pluck('destino')->unique();
$especies = $tansporCollect->pluck('especie')->unique();
$transporCollectUnique = $tansporCollectsinCosto->unique();
foreach($zonas as $zon){
$costoZona = $tansporCollect->where('zona',$zon);
foreach($destinos as $destin){
$costoDestino = $costoZona->where('destino',$destin);
foreach($especies as $espec){
$costoEspecie = $costoDestino->where('especie',$espec)->avg('costo');
/*HERE IM CALL OTHER FUNCTION */
$this->reemplazaCostoZona($zon, $destin, $espec, $costoEspecie, $transporCollectUnique);
}
}
}
}
I'm with laravel 5.8
You are not using the where function of collections correctly. For collections you need the following:
$productos = $transporCollect->where('zona', $zona)
->where('destino', $destino)
->where('especie',$especie)
->pluck('producto');
Hope that helps!

how to exchange data in laravel

I have the table structure below
how so that, if processed with the button, id_modul can change
id id_level id_modul
1 1 1
2 1 3
3 1 2
please, help me!
You can do something like this:
$module = Module::where('id_level', 1)->where('id_module', 3)->get();
$module->update(['id_module' => 1]);
like this
$foo_2 = Foo::where('id_modul', 2)->get();
$foo_3 = Foo::where('id_modul', 3)->get();
foreach ($foo_2 as $foo) {
$foo->id_modul = 3;
$foo->save();
}
foreach ($foo_3 as $foo) {
$foo->id_modul = 2;
$foo->save();
}

How to fetch users who does not have reports for 6 consecutive months using laravel?

I'm developing a report system, and I want to fetch users who did not report for six (6) consecutive months. How do I achieve this?
I've tried the code below but I'm not getting the desired output. There is also a problem. Let's say the date interval is 12 months. How can I determine if there is no report for 6 consecutive months?
$dateStart = '2018-10-31';
$dateEnd = '2019-03-31';
$intervals = Carbon::parse($dateStart)->diffInMonths($dateEnd);
$users = $users->whereDoesntHave('reports', function($query) use($intervals) {
for ($i = 5; $i >= 0; $i--) {
$firstMonth = Carbon::parse($dateEnd)->subMonthsNoOverflow($intervals);
$query->where('date', '>=', $firstMonth->format('Y-m-d'))->where('date', '<=', $dateEnd);
}
});
What I will do is that I will create a loop per month based on the start and end date, then check if he did not have a report for that month. If it doesn't have a report for that month, I will increment a counter, and if that counter reaches 6 counts, exit the loop and the condition was satisfied.
Below is the basic idea:
$dateStart = '2018-10-31';
$dateEnd = '2019-10-31';
$count = 0;
$no_report_for_6_consecutive_months = 0 ;
startloop
$have_report = Model::whereMonth('date_column', $date_of_loop->format('m'))->get();
if($have_report->count()){
$count = 0;
}
else{
$count++;
}
if($count==6){
$no_report_for_6_consecutive_months = 1 ;
break;
}
endloop
You have to find distinct users who report for six (6) consecutive and get difference with all users.
$enddate = 2019-04-15;
$startdate = date("Y-m-d", strtotime("-6 months", strtotime($enddate)));
$users = User::all();
$usersIdArray = $users->pluck("id")->all();
$reportedBy = Report::where('date', '>=', $startdate)
->where('date', '<=', $enddate)
->distinct("user_id")->get();
$reportedByIdArray = $reportedBy ->pluck("id")->all();
$notReportedByIdArray = array_values(array_diff($usersIdArray , $reportedByIdArray));
$notREportedUsers = User::whereIn(id", $notReportedByIdArray)->get();
//its a way but not tested
I have modified the query from this answer
I believe the query can be wrote cleaner. I will let you do this if you want to.
App\User::select('*')
->from(\DB::raw("(select
low.*,
low.`date` as date_start,
high.`date` as date_end,
to_days(high.`date`) - to_days(low.`date`) as day_gap,
period_diff(date_format(high.`date`, '%Y%m'),
date_format(low.`date`, '%Y%m')) as month_gap
from reports low, reports high
where high.`date` =
(select
min(`date`)
from reports
where
`date` > low.`date`
and low.user_id = high.user_id
)
) as d")
)->get();
Now you will get all the users with 4 extra fields: date_start; date_end, day_gap and month_gap
If you want the users with a month gap of 6 months you can do this:
App\User::select('*')
->from(\DB::raw("..."))
->where('month_gap', '>=', 6)
->get();

creating interactive charts using laravel

Please Help me i need pass this sql lines to a laravel syxtax to use
on customizable charts
Im using
https://github.com/ConsoleTVs/Charts
Sql Syntax:
SELECT
SUM(CASE WHEN status like 'Por Despachar' THEN 1 ELSE 0 END) AS Por_Despachar
,SUM(CASE WHEN status like 'Planificado' THEN 1 ELSE 0 END) AS Planificado
,SUM(CASE WHEN status like 'Despachado' THEN 1 ELSE 0 END) AS Despachado
FROM presupuesto
i want to add this parameter on interactive chart like this
enter image description here
This is my Controller:
<?php
namespace sisVentas\Http\Controllers;
use Illuminate\Http\Request;
use sisVentas\User;
use sisVentas\Http\Requests;
use Charts;
class EstadisticaController extends Controller
{
//
public function index()
{
$data = \DB::select("
SELECT
SUM(CASE WHEN status like 'Por Despachar' THEN 1 ELSE 0 END) AS Por_Despachar
,SUM(CASE WHEN status like 'Planificado' THEN 1 ELSE 0 END) AS Planificado
,SUM(CASE WHEN status like 'Despachado' THEN 1 ELSE 0 END) AS Despachado
FROM presupuesto
");
$chart = Charts::create('pie', 'highcharts')
// Setup the chart settings
->title("Resumen de Presupuestos Realizados")
// A dimension of 0 means it will take 100% of the space
// This defines a preset of colors already done:)
// You could always set them manually
// Setup the diferent datasets (this is a multi chart)
->labels(['Por Despachar', 'Despachado', 'Planificado'])
->values([65,10,20])
->dimensions(1000,500)
->responsive(false);
return dd($chart, $data);
}
}
Chart {#324 ▼
+id: null
+customId: null
+type: "pie"
+library: "highcharts"
+title: "Resumen de Presupuestos Realizados"
+element_label: "Element"
+labels: array:3 [▼
0 => "Por Despachar"
1 => "Despachado"
2 => "Planificado"
]
+values: array:3 [▼
0 => 65
1 => 10
2 => 20
]
+colors: []
+responsive: false
+gauge_style: "left"
+view: null
+region: "world"
#suffix: ""
+container: ""
+credits: false
+loader: true
+loader_duration: 500
+loader_color: "#000000"
+background_color: "inherit"
+template: "material"
+one_color: false
+legend: true
+x_axis_title: false
+y_axis_title: null
+"height": 500
+"width": 1000
}
array:1 [▼
0 => {#330 ▼
+"por_despachar": "3"
+"planificado": "1"
+"despachado": "0"
}
]
Maybe not direct answer but should be helpful
When you have any SQL query that is hard / impossible to convert into eloquent, just use DB facade.
$data = \DB::select("
SELECT
SUM(CASE WHEN status like 'Por Despachar' THEN 1 ELSE 0 END) AS Por_Despachar
,SUM(CASE WHEN status like 'Planificado' THEN 1 ELSE 0 END) AS Planificado
,SUM(CASE WHEN status like 'Despachado' THEN 1 ELSE 0 END) AS Despachado
FROM presupuesto
");
dd($data);
$chart = Charts::database($data, 'pie', 'highcharts')
->title('Amount subscribers')
->labels([Por_Despachar, Planificado, Despachado])
->values([$data[0]->Por_Despachar, $data[1]->Planificado, $data[2]->Despachado])
->dimensions(1000,500)
->responsive(true);

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

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();

Resources