How to combine two collections by matching keys and their values - laravel

So, I've been bashing my head against this for a while and I cant get it to just do what I need it to.
I want to be able to store a set of valuse in our database as Json, but no matter what I cant get Laravel or format the object quite right first.
I've got three queries, One gets users usernames and their First name, as an object. Another two use that object to get a count of each users sales, and quotes, from our databsae with count().
Now all I need is the objects to be combined.
array:1 [
"" => array:3 [
0 => array:7 [
0 => array:2 [
"CallCentreID" => "sdickerson"
"FirstName" => "Sarah"
]
1 => array:2 [
"CallCentreID" => "wjones"
"FirstName" => "Wendy"
]
2 => array:2 [
"CallCentreID" => "aknox"
"FirstName" => "Alex"
]
3 => array:2 [
"CallCentreID" => "mking"
"FirstName" => "Melissa"
]
4 => array:2 [
"CallCentreID" => "nrowecc"
"FirstName" => "Neil"
]
5 => array:2 [
"CallCentreID" => "ejones"
"FirstName" => "Emma"
]
6 => array:2 [
"CallCentreID" => "spurnell2"
"FirstName" => "Simon"
]
]
1 => array:5 [
0 => array:2 [
"CallCentreID" => "aknox"
"Sales" => 1169
]
1 => array:2 [
"CallCentreID" => "ejones"
"Sales" => 401
]
2 => array:2 [
"CallCentreID" => "mking"
"Sales" => 767
]
3 => array:2 [
"CallCentreID" => "sdickerson"
"Sales" => 1067
]
4 => array:2 [
"CallCentreID" => "wjones"
"Sales" => 716
]
]
2 => array:6 [
0 => array:2 [
"CallCentreID" => "aknox"
"Quotes" => 3587
]
1 => array:2 [
"CallCentreID" => "ejones"
"Quotes" => 400
]
2 => array:2 [
"CallCentreID" => "mking"
"Quotes" => 6975
]
3 => array:2 [
"CallCentreID" => "nrowecc"
"Quotes" => 3
]
4 => array:2 [
"CallCentreID" => "sdickerson"
"Quotes" => 2686
]
5 => array:2 [
"CallCentreID" => "wjones"
"Quotes" => 2734
]
]
]
]
The above is as close as I can get with the code I have which is;
$Users = User::where('Accesslevel', 'laravelcallcentre')->select('EmailAddress as CallCentreID', 'FirstName')->get();
$Sales = Order::groupBy('CallCentreID')
// ->whereDate('OrderDate', '=', date('2018-06-21'))
->whereIn('CallCentreID', $Users->pluck('CallCentreID'))
->where('Status', 'BOOKING')
->selectRaw('CallCentreID, count( * ) AS Sales')
->get();
$Quotes = Order::groupBy('CallCentreID')
// ->whereDate('OrderDate', '=', date('2018-06-21'))
->whereIn('CallCentreID', $Users->pluck('CallCentreID'))
->where('Status', 'QUOTE')
->selectRaw('CallCentreID, count( * ) AS Quotes')
->get();
$collection = collect([$Users, $Sales, $Quotes]);
$CCData = $collection->groupBy('CallCentreID');
Anyone got any better Ideas? I feel like im doing this completley wrong. I had this written out as a foreach loop but that ended up being four queries for every user, whihc stacked up fast.

$sales = $sales->keyBy('CallCentreID');
$quotes = $quotes->keyBy('CallCentreID');
$users = $users->map(function($user) use($sales,$quotes) {
$user->sales = isset($sales[$user['CallCentreID']]['sales']) ? $sales[$user['CallCentreID']]['sales'] : 0;
$user->quotes = isset($quotes[$user['CallCentreID']]['quotes']) ? $quotes[$user['CallCentreID']]['quotes'] : 0;
return $user;
});

Related

Laravel collection union during each not working

I have a probleme with union() that not insert my new collection
During my each I have the $mean collection with witch I search the slices() I test and have some $_availabaleSlices to insert into my $slices (id: 4 then id:7)
But after the whole code passed I only have the first $_availabaleSlices inside the $slices.
What I have made wrong ?
The code
$slices = new Collection();
Means::whereIn('id', $meansId)
->get()
->each(function ($mean) use (&$slices, $weight) {
$_availabaleSlices = $mean->slices()
->betweenWeight($weight)
->get();
if (0 < $_availabaleSlices->count()) {
dump('NEEDED',$_availabaleSlices->toArray());
dump('BEFORE',$slices->toArray());
$slices = $slices->union($_availabaleSlices);
dump('AFTER',$slices->toArray());
}
});
dd('RESULTS', $slices->toArray());
The Results
"NEEDED"
array:1 [
0 => array:5 [
"id" => 4
"deliveries_mean_id" => 3
"weight_min" => 250.0
"weight_max" => 600.0
"deleted_at" => null
]
]
"BEFORE"
[]
"AFTER"
array:1 [
0 => array:5 [
"id" => 4
"deliveries_mean_id" => 3
"weight_min" => 250.0
"weight_max" => 600.0
"deleted_at" => null
]
]
"NEEDED"
array:1 [
0 => array:5 [
"id" => 7
"deliveries_mean_id" => 4
"weight_min" => 150.0
"weight_max" => 700.0
"deleted_at" => null
]
]
"BEFORE"
array:1 [
0 => array:5 [
"id" => 4
"deliveries_mean_id" => 3
"weight_min" => 250.0
"weight_max" => 600.0
"deleted_at" => null
]
]
"AFTER"
array:1 [
0 => array:5 [
"id" => 4
"deliveries_mean_id" => 3
"weight_min" => 250.0
"weight_max" => 600.0
"deleted_at" => null
]
]
"RESULTS"
array:1 [
0 => array:5 [
"id" => 4
"deliveries_mean_id" => 3
"weight_min" => 250.0
"weight_max" => 600.0
"deleted_at" => null
]
]
Found the solution. I needed to use ->merge() and not ->union().

Compare two columns of a collection in laravel?

I want to compare two columns of a collection.I don't want to do this in db level, only in collection level.
I have a collection like this (I returned it in array model for readability)
array:3 [
0 => array:5 [
"total_amount" => 200000.0
"admin_max_amount" => "200000000"
]
1 => array:5 [
"total_amount" => 100000.0
"admin_max_amount" => "200000000"
]
2 => array:5 [
"total_amount" => 100000.0
"admin_max_amount" => "0"
]
]
I want to get first of them where total_amount > admin_max_amount.
Here is a more 'Laravel' way to do it:
$items = collect([
[
"total_amount" => 200000.0,
"admin_max_amount" => "200000000",
],
[
"total_amount" => 100000.0,
"admin_max_amount" => "200000000",
],
[
"total_amount" => 100000.0,
"admin_max_amount" => "0",
],
]);
$result = $items->first(function ($item)
{
return (float)$item['total_amount'] > (float)$item['admin_max_amount'];
});
dump($result);

Laravel Collection - Returning a total with sum() on nested arrays

I am trying to return a total using sum() by fetching the "duration" from each user within a $collection
The structure is
USER > CONTRACT_RESULTS > DAYS > DATE > ACTIVITIES > ACTIVITY
I want to query the "type" of activity and pull back the duration that is associated with that activity.
I had it working when it was much less nested using:
$collection->whereIn('activity',['off'])->sum('duration');
But I'm at a loss now since they are so nested and the names of the arrays are dynamic
Here is an example of the structure for 1 user in the $collection:
array:13 [▼
"user_id" => 52
"contract_results" => array:2 [▼
"2019-10-21 - 2019-10-31" => array:10 [▼
"hours_a_week" => "20"
"days" => array:1 [▼
"2019-10-21" => array:2 [▼
"bank_holiday" => "no"
"activities" => array:2 [▼
"10:00 - 22:00" => array:5 [▼
"type" => "driving"
"from" => "10:00"
"to" => "22:00"
"duration" => 720
"night_minutes" => 60
]
"22:00 - 00:00" => array:5 [▼
"type" => "driving"
"from" => "22:00"
"to" => "00:00"
"duration" => 120
"night_minutes" => 120
]
]
]
]
]
"2019-11-01 - 2019-11-10" => array:10 [▼
"hours_a_week" => "10"
"days" => array:1 [▼
"2019-11-01" => array:2 [▼
"bank_holiday" => "yes"
"activities" => array:1 [▼
"10:00 - 22:00" => array:5 [▼
"type" => "availability"
"from" => "10:00"
"to" => "22:00"
"duration" => 720
"night_minutes" => 60
]
]
]
]
]
]
]
I'm new to this so, thank you very much for your input!
Based on your unclear information, this is all that I can do:
$durationTotal = collect($data->get('contract_results'))
->transform(function ($contractResult) {
return array_merge((array) $contractResult, [
'days' => collect(data_get($contractResult, 'days'))
->transform(function ($day) {
return array_merge((array) $day, [
'activities' => collect(data_get($day, 'activities'))
->whereIn('type', ['driving'])
->toArray()
]);
})
->toArray()
]);
})
->sum(function ($item) {
return array_sum(data_get($item, 'days.*.activities.*.duration', []));
});

laravel result array of array

I have this eloquent query
$data= \App\Logs::select('id', 'created_at')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('d-M-');
})->toArray();
and this retun something like that
array:2 [▼
"06-Jul-" => array:1 [▼
0 => array:2 [▼
"id" => 1
"created_at" => "2017-07-06 13:21:15"
]
]
"07-Jul-" => array:3 [▼
0 => array:2 [▼
"id" => 2
"created_at" => "2017-07-07 13:43:23"
]
1 => array:2 [▼
"id" => 3
"created_at" => "2017-07-07 14:18:36"
]
2 => array:2 [▼
"id" => 4
"created_at" => "2017-07-07 14:18:41"
]
]
]
and i want return just the count
"06-Jul-" => "1"
"07-Jul-" => "3"
how i can do that?
You can use/chain map/transform after your groupBy for example:
$data = \App\Logs::select('id', 'created_at')
->get()
->groupBy(function($val) {
return Carbon::parse($val->created_at)->format('d-M-');
})
->transform(function ($collection, $key) {
return $collection->count();
});

Laravel multiple records update with Eloquent

I want to Update multiple records to the reference table. Here is the response of the $request.
array:21 [
"_method" => "PATCH"
"_token" => "xXukmVEsMvyeBODIURqFx9Mhk4LviYrV6iLmAuOY"
"account_type" => "0"
"name" => "test"
"model_id" => "2"
"location" => "USA"
"serial_no" => "00055555"
"status" => "Sales"
"capacity_lower" => ""
"weight" => "1212.000"
"category" => "1"
"attribute" => array:3 [
1 => array:1 [
1 => "1"
]
3 => array:2 [
3 => "5"
2 => "2"
]
4 => array:5 [
5 => "11"
6 => "13"
4 => "9"
7 => "23"
8 => "37"
]
]
"crane_manufacture_id" => "1"
"condition" => "Average"
"manufacture_year" => "2020"
"unit_no" => "222222"
"hours" => "100"
"video_url" => ""
"sub_category" => "4"
"description" => "dsfs"
"productImages" => array:7 [
0 => array:3 [
"id" => "27"
"descripton" => "89d9a500-a936-4510-9ca5-5952ee9c0bff.jpg"
"status_id" => "2"
]
1 => array:3 [
"id" => "28"
"descripton" => "89d9a500-a936-4510-9ca5-5952ee9c0bff.jpg"
"status_id" => "2"
]
2 => array:3 [
"id" => "29"
"descripton" => "89d9a500-a936-4510-9ca5-5952ee9c0bff.jpg"
"status_id" => "2"
]
3 => array:3 [
"id" => "30"
"descripton" => "89d9a500-a936-4510-9ca5-5952ee9c0bff.jpg"
"status_id" => "2"
]
4 => array:3 [
"id" => "31"
"descripton" => "89d9a500-a936-4510-9ca5-5952ee9c0bff.jpg"
"status_id" => "2"
]
5 => array:3 [
"id" => "32"
"descripton" => "89d9a500-a936-4510-9ca5-5952ee9c0bff.jpg"
"status_id" => "2"
]
6 => array:3 [
"id" => "33"
"descripton" => "89d9a500-a936-4510-9ca5-5952ee9c0bff.jpg"
"status_id" => "2"
]
]
]
I have two tables, Products and product_images. I have given relation that one product has multiple images. I have apply hasMany relationship in both table.
Now at the time of Update record I am follow the below code for updating product_images records.
DB::enableQueryLog();
$product = Product::find($id);
//$product->save($request->input());
$product->productImages()->update(new ProductImage($request->input('productImages')));
dd(DB::getQueryLog());
But I am facing error with "MassAssignmentException in Model.php line 452:
0"
Check your model both products and product_images has fillable property. refer docs
protected $fillable = ['list of columns to be inserted'];
Check the fillable property protected $fillable = []; or use for all properties from the $request protected $guarded = [];

Resources