Magento 2 Get product options id for sql query
-
12-03-2021 - |
Question
I have this query:
SELECT * FROM `sales_order_item` WHERE `product_options` LIKE '%2010%'
With the last bit being the decoded option id, I need to find two specific option ids to use inside this query.
My problem is that I can't load the options to be decoded.
json_decode($product->getOptions());
I've tried the above and got an error stating I'm using a object when it needs to be a string.
I need to be able to get the option ids from the decode json to filter the products ordered in the database with those option values.
Solution
Inject sales order item class in your constructor
protected $itemFactory;
public function __construct(
....
\Magento\Sales\Model\Order\ItemFactory $itemFactory,
....
) {
....
$this->itemFactory = $itemFactory;
....
}
then in your function add the below code to get values from it
try {
$order = $this->itemFactory->create()
->getCollection()
->addAttributeToFilter('product_options', array('like' => '%2010%'));
} catch (\Exception $e) {
error_log($e->getMessage());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange