I want to calculate avg in laravel using three table joins I've joined the tables perfectly and got the response from it but now I want to calculate the avg as well as count from the response I have got and then pass it to API response what should I do to achieve this?
Query i have tried
$individualScore= StatisticsMaster::with(['ratings',])->where('ratingsFor',$request->profileId)->get();
StatisticsMaster.php
public function ratings() {
return $this->hasMany(StatisticsChild::class,'statisticsMasterId','statisticsMasterId')->with('score');
}
StatisticsChild.php
public function score() {
return $this->belongsTo(Skill::class,'skillId','skillId');
}
public function getSkillNameAttribute(){
return $this->score->skillName;
}
DB Structure I have
tblSkills
->skillId
->skillName
->skillStatus
tblStatisticsMaster
->statisticsMasterId
->ratingsFor
->ratingsBy
->status
tblStatisticsChild
->statisticsChildId
->skillId
->statisticsMasterId
->individualScore
->statisticsStatus
I have got this response
{
"meta": {
"code": "200",
"message": "Skill Fetched Successfully."
},
"data": {
"skills": [
{
"statisticsMasterId": 1,
"ratingsFor": 1,
"ratingsBy": 6,
"score": 60.8,
"ratings": [
{
"skillId": 1,
"individualScore": 86,
"statisticsStatus": 1,
"skillName": "Shooting"
},
{
"skillId": 2,
"individualScore": 70,
"statisticsStatus": 1,
"skillName": "Dribbling"
},
{
"skillId": 3,
"individualScore": 54,
"statisticsStatus": 1,
"skillName": "Passing"
},
{
"skillId": 4,
"individualScore": 44,
"statisticsStatus": 1,
"skillName": "Defense"
},
{
"skillId": 5,
"individualScore": 50,
"statisticsStatus": 1,
"skillName": "Good Teammate"
}
]
},
{
"statisticsMasterId": 2,
"ratingsFor": 1,
"ratingsBy": 2,
"score": 52,
"ratings": [
{
"skillId": 1,
"individualScore": 50,
"statisticsStatus": 1,
"skillName": "Shooting"
},
{
"skillId": 2,
"individualScore": 50,
"statisticsStatus": 1,
"skillName": "Dribbling"
},
{
"skillId": 3,
"individualScore": 60,
"statisticsStatus": 1,
"skillName": "Passing"
},
{
"skillId": 4,
"individualScore": 50,
"statisticsStatus": 1,
"skillName": "Defense"
},
{
"skillId": 5,
"individualScore": 50,
"statisticsStatus": 1,
"skillName": "Good Teammate"
}
]
}
]
}
}
and the response I want.
{
"meta": {
"code": "200",
"message": "Skill Fetched Successfully."
},
"data": {
"skills": [
{
"statisticsMasterId": 1,
"ratingsFor": 1,
"ratingsBy": 6,
"score": 56.4,
"ratings": [
{
"skillId": 1,
"individualScore": 86,
"statisticsStatus": 1,
"skillName": "Shooting"
},
{
"skillId": 2,
"individualScore": 70,
"statisticsStatus": 1,
"skillName": "Dribbling"
},
{
"skillId": 3,
"individualScore": 54,
"statisticsStatus": 1,
"skillName": "Passing"
},
{
"skillId": 4,
"individualScore": 44,
"statisticsStatus": 1,
"skillName": "Defense"
},
{
"skillId": 5,
"individualScore": 50,
"statisticsStatus": 1,
"skillName": "Good Teammate"
}
]
}
]
}
}
where all the individual score contains the avg of all the ratings I'm using eloquent I want to do this in eloquent itself. how can I achieve this?
Thanks in advance :)
Related
I want to modify nested collection using group by.
This is sample collection
"document": [
{
"id": 1,
"company_id": 4,
"client_id": 1,
"status": 1,
"client": {
"id": 1,
"company_id": 4,
"name": "1663159185735-client"
},
"document_items": [
{
"id": 1,
"master_id": 5,
"text_value": "piyo",
},
{
"id": 2,
"master_id": 5,
"text_value": "fuga",
},
{
"id": 3,
"master_id": 3,
"text_value": "hoge",
}
]
}
]
I want to change like this.
"document": [
{
"id": 1,
"company_id": 4,
"client_id": 1,
"status": 1,
"client": {
"id": 1,
"company_id": 4,
"name": "1663159185735-client"
},
"document_items": [
5: [{
"id": 1,
"master_id": 5,
"text_value": "piyo",
},
{
"id": 2,
"master_id": 5,
"text_value": "fuga",
}
],
3: [{
"id": 2,
"master_id": 5,
"text_value": "fuga",
}
]
]
}
]
I try write below code;
$result->map(function ($v){
$v->documentItems = $v->documentItems->groupBy('master_id');
return $v;
});
but output key is documentItems not document_items
I changed to
$v->document_items = $v->documentItems->groupBy('master_id');
key is drawing_drawing_items but not groupby(simple array)
how to modify group by and preserve key case?
I changed to
$v->document_items = $v->documentItems->groupBy('master_id');
key is drawing_drawing_items but not groupby(simple array)
You should also change like this $v->document_items->groupBy('master_id')
The key is 'document_items' not 'documentItems'
I need to remove the 'data' key from my collection in Laravel.
This worked for me, but it removed the other keys that I cared to keep, I just need to remove the 'data' key:
return $filteredValues = $collection->values ()->all(); // I remove other keys inside the objects.
My collection return:
$records = Item::where('tienda_id',$id)->where('item.nombre', 'like', "%" . $query . "%")->take(50)->get();
return $collection = new ItemCollection($records);
My ItemCollection.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Facades\Storage;
class ItemCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* #param \Illuminate\Http\Request $request
* #return mixed
*/
public function toArray($request)
{
return $this->collection->transform(function($row, $key) {
return [
'id' => $row->id,
'nombre' => $row->nombre,
'marca_id' => $row->marca_id,
'tienda_id' => $row->tienda_id,
'nombre_marca' => $row->marca->nombre_marca,
'unidad_id' => $row->unidad_id,
'nombre_unidad' => $row->unidad->nombre_unidad,
'tipo_cambio' => $row->tienda->tipocambio,
'categoria_id' => $row->categoria_id,
'stock' => $row->stock,
'moneda' => $row->moneda,
'codigos' => $row->codigos,
'stockminimo' => $row->stockminimo,
'stockmaximo' => $row->stockmaximo,
'impuesto_id' => $row->impuesto_id,
'primer_margen' => $row->primer_margen,
'segundo_margen' => $row->segundo_margen,
'precio' => $row->precio,
'notas' => $row->notas,
'imagen' => url('images/'.$row->imagen),
];
});
}
}
My JSON:
{
"data": [
{
"id": 27,
"nombre": "Nombre de prueba",
"marca_id": 2,
"tienda_id": 2,
"nombre_marca": "marca 2",
"unidad_id": 59,
"nombre_unidad": "NIU",
"tipo_cambio": "3.54",
"categoria_id": 1,
"stock": 100,
"moneda": "$",
"codigos": [
{
"id": 2,
"nombre_codigo": "Codigo",
"tienda_id": 2,
"created_at": "2020-08-03T15:19:11.000000Z",
"updated_at": "2020-08-06T22:38:02.000000Z",
"pivot": {
"item_id": 27,
"codigo_id": 2,
"nombre": "66677kj"
}
},
{
"id": 5,
"nombre_codigo": "CODIGO 2",
"tienda_id": 2,
"created_at": "2020-08-07T20:45:29.000000Z",
"updated_at": "2020-08-07T20:45:29.000000Z",
"pivot": {
"item_id": 27,
"codigo_id": 5,
"nombre": "78877k"
}
}
],
"stockminimo": 1,
"stockmaximo": 100,
"impuesto_id": 1,
"primer_margen": "35.00",
"segundo_margen": "20.00",
"precio": "5.07",
"notas": "jkjkkjkkj",
"imagen": "http://maks.test/images/159692202782450637_121718839341269_2075616741920079872_o.jpg"
},
{
"id": 28,
"nombre": "Aleta de pollo",
"marca_id": 1,
"tienda_id": 2,
"nombre_marca": "marca1x",
"unidad_id": 59,
"nombre_unidad": "NIU",
"tipo_cambio": "3.54",
"categoria_id": 1,
"stock": 5,
"moneda": "S/",
"codigos": [
{
"id": 2,
"nombre_codigo": "Codigo",
"tienda_id": 2,
"created_at": "2020-08-03T15:19:11.000000Z",
"updated_at": "2020-08-06T22:38:02.000000Z",
"pivot": {
"item_id": 28,
"codigo_id": 2,
"nombre": "jhjjkj"
}
},
{
"id": 5,
"nombre_codigo": "CODIGO 2",
"tienda_id": 2,
"created_at": "2020-08-07T20:45:29.000000Z",
"updated_at": "2020-08-07T20:45:29.000000Z",
"pivot": {
"item_id": 28,
"codigo_id": 5,
"nombre": "jkk"
}
}
],
"stockminimo": 6,
"stockmaximo": 88,
"impuesto_id": 1,
"primer_margen": "2.00",
"segundo_margen": "10.00",
"precio": "100.00",
"notas": "jkjkkjjk",
"imagen": "http://maks.test/images/159698573182341068_123146022531884_1345097685962588160_o.jpg"
}
]
}
I need it to look like this:
[
{
"id": 27,
"nombre": "Nombre de prueba",
"marca_id": 2,
"tienda_id": 2,
"nombre_marca": "marca 2",
"unidad_id": 59,
"nombre_unidad": "NIU",
"tipo_cambio": "3.54",
"categoria_id": 1,
"stock": 100,
"moneda": "$",
"codigos": [
{
"id": 2,
"nombre_codigo": "Codigo",
"tienda_id": 2,
"created_at": "2020-08-03T15:19:11.000000Z",
"updated_at": "2020-08-06T22:38:02.000000Z",
"pivot": {
"item_id": 27,
"codigo_id": 2,
"nombre": "66677kj"
}
},
{
"id": 5,
"nombre_codigo": "CODIGO 2",
"tienda_id": 2,
"created_at": "2020-08-07T20:45:29.000000Z",
"updated_at": "2020-08-07T20:45:29.000000Z",
"pivot": {
"item_id": 27,
"codigo_id": 5,
"nombre": "78877k"
}
}
],
"stockminimo": 1,
"stockmaximo": 100,
"impuesto_id": 1,
"primer_margen": "35.00",
"segundo_margen": "20.00",
"precio": "5.07",
"notas": "jkjkkjkkj",
"imagen": "http://maks.test/images/159692202782450637_121718839341269_2075616741920079872_o.jpg"
},
{
"id": 28,
"nombre": "Aleta de pollo",
"marca_id": 1,
"tienda_id": 2,
"nombre_marca": "marca1x",
"unidad_id": 59,
"nombre_unidad": "NIU",
"tipo_cambio": "3.54",
"categoria_id": 1,
"stock": 5,
"moneda": "S/",
"codigos": [
{
"id": 2,
"nombre_codigo": "Codigo",
"tienda_id": 2,
"created_at": "2020-08-03T15:19:11.000000Z",
"updated_at": "2020-08-06T22:38:02.000000Z",
"pivot": {
"item_id": 28,
"codigo_id": 2,
"nombre": "jhjjkj"
}
},
{
"id": 5,
"nombre_codigo": "CODIGO 2",
"tienda_id": 2,
"created_at": "2020-08-07T20:45:29.000000Z",
"updated_at": "2020-08-07T20:45:29.000000Z",
"pivot": {
"item_id": 28,
"codigo_id": 5,
"nombre": "jkk"
}
}
],
"stockminimo": 6,
"stockmaximo": 88,
"impuesto_id": 1,
"primer_margen": "2.00",
"segundo_margen": "10.00",
"precio": "100.00",
"notas": "jkjkkjjk",
"imagen": "http://maks.test/images/159698573182341068_123146022531884_1345097685962588160_o.jpg"
}
]
Thanks in advance for reading me, I hope you can help me solve this problem, thanks!
In AppProvider.php or similar add the following. This will disable data wrapping, for ItemCollections. Thou i would want you to reconsider, if you need to use pagination or meta attributes on your responses, you have no where to put em withouth data wrapping and thats one of the reason it is used.
public function boot()
{
ItemCollection::withoutWrapping();
}
I currently have the below json response that the API is returning. I am able to return it using Laravel Eloquent. There are several users and each user has a several receipts. A receipt has types and status. I want to try to get the total sum amount for each receipt that is related to its type and status. I was able to return the below json response using
$this->user->with('receipts')->has('receipts')->get(['id', 'name']);
I have tried using multiple laravel collections methods https://laravel.com/docs/5.8/collections#available-methods But I am still unable to get the desired response.
[
{
"id": 1,
"name": "kent",
"receipts": [
{
"id": 1,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 100
},
{
"id": 2,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 100
},
{
"id": 3,
"user_id": 1,
"type_id": 2,
"status": 1,
"amount": 50
},
{
"id": 4,
"user_id": 1,
"type_id": 2,
"status": 0,
"amount": 30
},
{
"id": 5,
"user_id": 1,
"type_id": 2,
"status": 0,
"amount": 30
},
{
"id": 6,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 20
},
{
"id": 7,
"user_id": 1,
"type_id": 1,
"status": 1,
"amount": 10
}
]
},
{
"id": 2,
"name": "allison",
"receipts": [
{
"id": 9,
"user_id": 2,
"type_id": 1,
"status": 0,
"amount": 20
}
]
}
]
I expect to get this:
[
{
"id": 1,
"name": "kent",
"receipts": [
{
"performance and deleted": 220,
"performance and not deleted": 10,
"project and deleted": 60,
"project and deleted": 50
}
]
},
{
"id": 2,
"name": "allison",
"receipts": [
{
"performance and deleted": 20,
"performance and not deleted": 0,
"project and deleted": 0,
"project and not deleted": 0
}
]
}
]
My main concern is to use laravel collection methods and easy to read code to get my expected result
In this way, I believe you get your expected result with nice readable code.
I'll assume that you have $users variable which contains a list of users in collection (And probably the receipts are already loaded).
// You need to name the keys as you desire. (I can't figure out the labels by the type_id and status numbers).
$statusPair = collect([
'performance and deleted' => [
'type_id' => 1,
'status' => 0,
],
'something' => [
'type_id' => 1,
'status' => 1,
],
'something 2' => [
'type_id' => 2,
'status' => 0,
],
'something 3' => [
'type_id' => 2,
'status' => 1,
],
]);
$data = $users->map(function ($user) use ($statusPair) {
$receipts = $user->receipts;
$sums = $statusPair->mapWithKeys(function ($pair, $statusLabel) use ($receipts) {
$filtered = $receipts;
foreach ($pair as $key => $value) {
$filtered = $filtered->where($key, $value);
}
$sum = $filtered->sum('amount');
return [
$statusLabel => $sum,
];
});
return [
'id' => $user->id,
'name' => $user->name,
'receipts' => $sums->toArray(),
];
});
i think this will help
$user->receipts->sum('amount');
Laravel custom pagination page 2 result return as object not array.
This is my code of custom pagination
function custom_paginate($data)
{
//Get current page form url e.g. &page=6
$currentPage = LengthAwarePaginator::resolveCurrentPage();
//Create a new Laravel collection from the array data
$collection = new Collection($data);
//Define how many items we want to be visible in each page
$per_page = (int) per_page();
//Slice the collection to get the items to display in current page
$currentPageResults = $collection->slice(($currentPage - 1) * $per_page, $per_page)->all();
//Create our paginator and add it to the data array
$data['results'] = new LengthAwarePaginator($currentPageResults, count($collection), $per_page);
//Set base url for pagination links to follow e.g custom/url?page=6
return $data['results']->setPath(request()->url());
}
when i am at page 1 data is coming as array but in same code if i passed page=2result is coming as object.
Expected result
{
"current_page": 2,
"data": [
{
"_id": 34,
"state": "Andaman & Nicobar Islands",
"post_count": 8,
"totalPhotos": 0,
"totalVideos": 1,
"totalAudios": 0
},
{
"_id": 28,
"state": "Andhra Pradesh",
"post_count": 888,
"totalPhotos": 0,
"totalVideos": 111,
"totalAudios": 0
},
{
"_id": 12,
"state": "Arunachal Pradesh",
"post_count": 200,
"totalPhotos": 0,
"totalVideos": 25,
"totalAudios": 0
},
{
"_id": 18,
"state": "Assam",
"post_count": 464,
"totalPhotos": 0,
"totalVideos": 58,
"totalAudios": 0
},
{
"_id": 10,
"state": "Bihar",
"post_count": 1072,
"totalPhotos": 0,
"totalVideos": 134,
"totalAudios": 0
}
],
"first_page_url": "http://swachh-manch-data.git/insight/posts?page=1",
"from": 6,
"last_page": 8,
"last_page_url": "http://swachh-manch-data.git/insight/posts?page=8",
"next_page_url": "http://swachh-manch-data.git/insight/posts?page=3",
"path": "http://swachh-manch-data.git/insight/posts",
"per_page": 5,
"prev_page_url": "http://swachh-manch-data.git/insight/posts?page=1",
"to": 10,
"total": 36
}
but getting data as object on page 2 (Actual result)
{
"current_page": 2,
"data": {
"5": {
"_id": 4,
"state": "Chandigarh",
"post_count": 8,
"totalPhotos": 0,
"totalVideos": 1,
"totalAudios": 0
},
"6": {
"_id": 22,
"state": "Chhattisgarh",
"post_count": 1336,
"totalPhotos": 0,
"totalVideos": 167,
"totalAudios": 0
},
"7": {
"_id": 26,
"state": "Dadra & Nagar Haveli",
"post_count": 8,
"totalPhotos": 0,
"totalVideos": 1,
"totalAudios": 0
},
"8": {
"_id": 25,
"state": "Daman & Diu",
"post_count": 16,
"totalPhotos": 0,
"totalVideos": 2,
"totalAudios": 0
},
"9": {
"_id": 7,
"state": "Delhi",
"post_count": 40,
"totalPhotos": 0,
"totalVideos": 5,
"totalAudios": 0
}
},
"first_page_url": "http://swachh-manch-data.git/insight/posts?page=1",
"from": 6,
"last_page": 8,
"last_page_url": "http://swachh-manch-data.git/insight/posts?page=8",
"next_page_url": "http://swachh-manch-data.git/insight/posts?page=3",
"path": "http://swachh-manch-data.git/insight/posts",
"per_page": 5,
"prev_page_url": "http://swachh-manch-data.git/insight/posts?page=1",
"to": 10,
"total": 36
}
i am not sure but the problem is in $currentPageResults = $collection->slice(($currentPage - 1) * $per_page, $per_page)->all(); this line.
Thanks in advance. :)
Change
$currentPageResults = $collection->slice(($currentPage - 1) * $per_page, $per_page)->all();
to
$currentPageResults = $collection->slice(($currentPage - 1) * $per_page, $per_page)->values();
for more info read this.
Simply i have queried an api to return some data for a game. The result is an array where each set contains epoch datecreated field.
Using php i want to be able to filter out all the data for only data containing datecreated > 1444639042(epoch time).
How is that possible?
I am using leaguewrap from github as my class to pull data so:
// Get Match History
$game = $api->game();
$games = $game->recent($loluser);
returns:
{
"games": [
{
"fellowPlayers": [
{
"championId": 84,
"teamId": 200,
"summonerId": 4972120
},
{
"championId": 23,
"teamId": 200,
"summonerId": 1011313
},
{
"championId": 18,
"teamId": 100,
"summonerId": 456905
},
{
"championId": 77,
"teamId": 100,
"summonerId": 2751172
},
{
"championId": 131,
"teamId": 100,
"summonerId": 5100445
},
{
"championId": 1,
"teamId": 200,
"summonerId": 841536
},
{
"championId": 99,
"teamId": 200,
"summonerId": 4400359
},
{
"championId": 18,
"teamId": 200,
"summonerId": 3652614
},
{
"championId": 80,
"teamId": 100,
"summonerId": 600691
}
],
"gameType": "MATCHED_GAME",
"stats": {
"totalDamageDealtToChampions": 17713,
"goldEarned": 11117,
"item1": 3174,
"wardPlaced": 15,
"totalDamageTaken": 19563,
"item0": 1056,
"trueDamageDealtPlayer": 4,
"physicalDamageDealtPlayer": 10423,
"trueDamageDealtToChampions": 4,
"killingSprees": 1,
"playerRole": 2,
"totalUnitsHealed": 3,
"playerPosition": 4,
"level": 16,
"magicDamageDealtToChampions": 16682,
"turretsKilled": 2,
"magicDamageDealtPlayer": 81369,
"neutralMinionsKilledEnemyJungle": 3,
"assists": 9,
"magicDamageTaken": 11659,
"numDeaths": 5,
"totalTimeCrowdControlDealt": 326,
"largestMultiKill": 1,
"physicalDamageTaken": 7526,
"sightWardsBought": 2,
"team": 100,
"win": false,
"totalDamageDealt": 91797,
"largestKillingSpree": 5,
"totalHeal": 2398,
"item4": 3135,
"item3": 3020,
"item6": 3340,
"item5": 3165,
"minionsKilled": 59,
"timePlayed": 2852,
"physicalDamageDealtToChampions": 1025,
"championsKilled": 5,
"trueDamageTaken": 377,
"goldSpent": 9620,
"neutralMinionsKilled": 3
},
"gameId": 107038398,
"ipEarned": 82,
"spell1": 3,
"teamId": 100,
"spell2": 7,
"gameMode": "CLASSIC",
"mapId": 11,
"level": 30,
"invalid": false,
"subType": "NORMAL",
"createDate": 1444289569012,
"championId": 99
}
]}