Hello everyone
I have been searching through the documentation, as I am convinced there is an Eloquent way of doing what I am trying to do but can't seem to find it.
I have three tables that looks like that:
- users: id, ...
- orders: id, user_id, ...
- order_items: id, order_id, product_id, ...
Essentially a user has many orders, and an order has many items.
My goal is to retrieve every purchased products (products id) from all the orders of a user.
I would like to avoid doing the following,
$userOrders = \App\User::with(['orders', 'orders.items'])
->findOrFail($userId);
// This way of doing works..but it does not feel right
$product_ids = [];
foreach($userOrders->orders as $order) {
foreach($order->items as $item) {
$product_ids []= $item->product_id;
}
}
$purchased_products_ids = array_unique($product_ids);
//var_dump($purchased_products_ids);
// This does not work however I have the impression that the proper way of doing it
// would be somewhat similar to this?
// This throws an error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'orders.items.product_id'
// I also tried plucking only product_id, or just items.product_id, to no avail.
// $p = $userOrders->pluck('orders.items.product_id');
$p = $userOrders->get()->pluck('orders.items.product_id');
Is pluck even the proper method to use to achieve what I want?
Any suggestions or guidance would be appreciated
Thank you very much