Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I find out what orders belong to a user? #10

Closed
dhilowitz opened this issue Sep 28, 2020 · 3 comments
Closed

How do I find out what orders belong to a user? #10

dhilowitz opened this issue Sep 28, 2020 · 3 comments
Labels
help wanted Extra attention is needed question Further information is requested

Comments

@dhilowitz
Copy link

It would be great to have some basic documentation for this plugin. I'm looking for answers to the following questions:

  • Given a user ID, how do I find out what orders belong to them?
  • Given a user ID, how do I find out which products they have purchased?
  • Given a product, how do I find out whether or not a user has purchased said product?
@Dartui
Copy link
Collaborator

Dartui commented Sep 28, 2020

Given a user ID, how do I find out what orders belong to them:

use Corcel\WooCommerce\Model\Order;

Order::hasMeta('_customer_user', 1)->get(); // 1 - customer ID

Given a user ID, how do I find out which products they have purchased

use Corcel\WooCommerce\Model\Order;

// get orders and eager load items with product to optimize queries count
$orders   = Order::with('items.product')->hasMeta('_customer_user', 1)->get();
$items    = $orders->pluck('items')->flatten(1); // all items from orders
$products = $items->pluck('product');            // all products from all orders (non-unique)

Unfortunately relation from product to orders is not yet implemented, so your third question cannot be solved right now. PRs are welcome.

@Dartui Dartui added help wanted Extra attention is needed question Further information is requested labels Sep 28, 2020
@dhilowitz
Copy link
Author

dhilowitz commented Sep 29, 2020 via email

@Dartui
Copy link
Collaborator

Dartui commented Oct 3, 2020

Given a product, how do I find out whether or not a user has purchased said product:

With the last commit from master you can do it for example in this way:

$product   = Product::find(1);
$orders    = $product->items->pluck('order');
$orders    = $orders->filter(function ($order) {
    return $order->hasMeta('_customer_id', 1);
});
$wasBought = $orders->isNotEmpty();

I will close this issue. Any work with documentation will be continued in this issue: #11

@Dartui Dartui closed this as completed Oct 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants