I have the following tables and want to get all units (base unit, and sub units) of the product
Units
id | name | multiplier | base_unit_id |
---|---|---|---|
1 | Piece | 1 | null |
2 | Dozen - 12 | 12 | 1 |
Products
id | name | cost | price | unit_id |
---|---|---|---|---|
1 | product1 | 10 | 14 | 1 |
1 | product2 | 10 | 14 | 1 |
Relationship inside Product Model
public function units()
{
return $this->belongsTo(Unit::class, 'unit_id', 'id'); // Or where base_unit_id = product unit id
// I have tried this
// $this->belongsTo(Unit::class, 'unit_id', 'id')->orWhere('base_unit_id', $this->unit_id)
// Does not work
}
I like to get the products like so
$products = Product::with('units')->get();
Expected output is
[
{
"id": 1,
"name": "Product 1",
"unit_id": 1,
"cost": 10,
"price": 14,
"units": [
{
"id": 1,
"name": "Piece",
"multiplier": 1,
"base_unit_id": null
},
{
"id": 1,
"name": "Dozen - 12",
"multiplier": 12,
"base_unit_id": 1
}
]
},
{
"id": 1,
"name": "Product 2",
"unit_id": 1,
"cost": 10,
"price": 14,
"units": [
{
"id": 1,
"name": "Piece",
"multiplier": 1,
"base_unit_id": null
},
{
"id": 1,
"name": "Dozen - 12",
"multiplier": 12,
"base_unit_id": 1
}
]
}
]
I want the units in one list how can I do this?