I am at the moment calling a few nested relations. But what I am trying to do is to get all the columns with the same "measured_at" date in one array instead of them being spread.
A brief example of the structure that I am getting:
{
"id": 1,
"user_body_sizes": [
{
"id": 23,
"measured_at": "2023-04-04"
},
{
"id": 24,
"measured_at": "2023-04-04"
},
{
"id": 26,
"measured_at": "2023-03-14"
},
{
"id": 29,
"measured_at": "2023-03-14"
}
]
}
So this is what I actually want to achieve:
{
"id": 1,
"user_body_sizes": [
[
{
"id": 23,
"measured_at": "2023-04-04"
},
{
"id": 24,
"measured_at": "2023-04-04"
}
],
[
{
"id": 29,
"measured_at": "2023-03-14"
},
{
"id": 26,
"measured_at": "2023-03-14"
}
]
]
}
So basically I want the data with the same "measured_at" date to be in the same array.
So in Laravel this is my code at the moment to get the data:
public function GetCustomerBodySize($customerId, $month, $year)
{
$customerUserId = Customer::findOrFail($customerId)['user'];
return CustomerBodySize::with([ 'customer_data.user_body_sizes.body_parts','customer_data.user_body_sizes' => function ($q) use ($month, $year){
$q->whereMonth('measured_at', '=', $month);
$q->whereYear('measured_at', '=', $year);
$q->orderBy('measured_at');
}])
->whereRelation('customer_data', 'id', $customerUserId)
->first();
}
And here are my relations:
// This is in my CustomerBodySize model
function customer_data(){
return $this->belongsTo(User::class, 'customer');
}
function body_parts(){
return $this->belongsTo(BodyParts::class, 'body_part');
}
// This is in my User model
public function user_body_sizes(){
return $this->hasMany(CustomerBodySize::class, 'customer');
}
2
Answers
you can use
Laravel's
Collection’sgroupBy()
method to group theuser_body_sizes
by theirmeasured_at
datewe are first
fetching all
the relevantCustomerBodySize
records with the given filters usingget()
instead offirst()
And then we make group
user_body_sizes
by theirmeasured_at
date using thegroupBy()
methodAt last, we use
map()
to return an array of arrays, with eachnested
array containing theCustomerBodySize
records that share the samemeasured_at date
. We also usevalues()
to remove thegrouping keys
from theresulting collection
.If there are no records matching the given filters, we return
null
.Modified Code is Here