У меня есть API ресурсов, который дает мне результат, но я хочу сгруппировать их на основе модели отношений.
Код
controller
$outlet = Outlet::where('slug', $slug)->with(['barcodes.product', 'damages', 'images'])->first();
result
{
"data": {
"id": 1,
"name": "Outlet One",
"slug": "outlet-one",
"address": "Jl Raya Bogor No.200",
"cover": null,
"phone": "0211111112",
"products": [
{
"id": 1,
"sku": "AB001SU",
"serial_number": 5245412185,
"price": 120000,
"discount": null,
"product": {
"id": 1,
"name": "Product One",
"slug": "product-one",
"stock": "70",
"cover": null,
"description": "This is first product description.",
"sku": "AB001SU",
"price": 120000,
"discount": null
}
},
{
"id": 2,
"sku": "FD51",
"serial_number": 778516,
"price": 75300,
"discount": 5300,
"product": {
"id": 1,
"name": "Product One",
"slug": "product-one",
"stock": "70",
"cover": null,
"description": "This is first product description.",
"sku": "AB001SU",
"price": 120000,
"discount": null
}
},
{
"id": 3,
"sku": "7609FS",
"serial_number": 232547544,
"price": 35900,
"discount": null,
"product": {
"id": 2,
"name": "Product Two",
"slug": "product-two",
"stock": "120",
"cover": null,
"description": "This is second product description.",
"sku": "FRY8016",
"price": 450000,
"discount": 50000
}
}
]
},
"message": "Outlet retrieved successfully."
}
Как вы можете видеть в products": [...]
id 1 and 2
принадлежат Product One
, могу ли я сгруппировать по моей barcodes.product
на основе product
модели?
Обновление
Для большей ясности; Я ищу что-то вроде этого:
{
"data": {
"id": 1,
"name": "Outlet One",
"slug": "outlet-one",
"address": "Jl Raya Bogor No.200",
"cover": null,
"phone": "0211111112",
"products": [
{
"id": 1,
"name": "Product One",
"slug": "product-one",
"stock": "70",
"cover": null,
"description": "This is first product description.",
"sku": "AB001SU",
"price": 120000,
"discount": null
"barcodes": { // now barcodes are grouped by prodcuts
"id": 1,
"sku": "AB001SU",
"serial_number": 5245412185,
"price": 120000,
"discount": null,
},
{
"id": 2,
"sku": "FD51",
"serial_number": 778516,
"price": 75300,
"discount": 5300,
},
},
{
"id": 2,
"name": "Product Two",
"slug": "product-two",
"stock": "120",
"cover": null,
"description": "This is second product description.",
"sku": "FRY8016",
"price": 450000,
"discount": 50000
"barcodes": { // now barcodes are grouped by prodcuts
"id": 3,
"sku": "7609FS",
"serial_number": 232547544,
"price": 35900,
"discount": null,
}
}
]
},
"message": "Outlet retrieved successfully."
}
Обновление 2
Outlet model
public function barcodes()
{
return $this->belongsToMany(Barcode::class, 'outlet_products');
}
Barcode model
public function outlets()
{
return $this->belongsToMany(Outlet::class, 'outlet_products');
}
public function product()
{
return $this->belongsTo(Product::class);
}