An Order
have many ordered items
An Order
's ordered items can either be a User
or Product
What I am looking for is a way to retrieve all morphed objects to an Order
. Instead of $order->users
or $order->products
I would like to do $order->items
.
My progress
My progress so far involves a Many To Many Polymorphic Relationship.
My tables:
orders
id - integer
orderables (the order items)
order_id - integer
orderable_id - integer
orderable_type - string
quantity - integer
price - double
-----------
users
id - integer
name - string
products
id - integer
name - string
Example on how orderables
table look
This is how I create an order and add a user and a product:
/**
* Order
* @var Order
*/
$order = new App\Order;
$order->save();
/**
* Add user to order
* @var [type]
*/
$user = \App\User::find(1);
$order->users()->sync([
$user->id => [
'quantity' => 1,
'price' => $user->price()
]
]);
/**
* Add product to order
* @var [type]
*/
$product = \App\product::find(1);
$order->products()->sync([
$product->id => [
'quantity' => 1,
'price' => $product->price()
]
]);
Order.php
/**
* Ordered users
* @return [type] [description]
*/
public function users() {
return $this->morphedByMany('Athliit\User', 'orderable');
}
/**
* Ordered products
*/
public function products() {
return $this->morphedByMany('Athliit\Product', 'orderable');
}
Currently I can do
foreach($order->users as $user) {
echo $user->id;
}
Or..
foreach($order->products as $product) {
echo $product->id;
}
But I would like to be able to do something along the lines of...
foreach($order->items as $item) {
// $item is either User or Product class
}
I have found this question, which was the closest I could find to what I am trying to do, but I can't make it work in regards to my needs, it is outdated, and also seems like a very hacky solution.
Have a different approach?
If you have a different approach than Polymorphic relationships, please let me know.