Magento2 - How To Load Product by SKU in Magento 2
Magento2 - How To Load Product by SKU in Magento 2
_
Magento Stack Exchange is a question Here's how it works:
and answer site for users of the
Magento e-Commerce platform. Join
them; it only takes a minute:
Sign up Anybody can ask Anybody can The best answers are voted
a question answer up and rise to the top
It's pretty basic, but I cant nd a working example on Stackexchange or google. I want to load a product from a helper or block. I already tried
some things like:
$objectManager=\Magento\Framework\App\ObjectManager::getInstance()
$product=$objectManager>create('\Magento\Catalog\Api\Data\ProductInterface')
$product>get('<SKU>')
$product>getName()
This returns nothing. I also tried loading any available models and APIs, but nothing seems to work with SKUs.
magento2 product
3 Answers
$product=$this>productRepositoryInterface>get($sku)
Full example:
...
private$productRepository
...
publicfunction__construct(
...
\Magento\Catalog\Api\ProductRepositoryInterface$productRepository
...
){
...
$this>productRepository=$productRepository
...
}
publicfunctionloadMyProduct($sku)
{
return$this>productRepository>get($sku)
}
...
3 This method gives an error when no product is found. So for checking if an product exists, It seems @fschmengler's
solution might be the better way to go. Dennis van Schaik Apr 20 '16 at 11:00
publicfunction__construct(\Magento\Catalog\Model\ProductFactory$productFactory)
{
$this>productFactory=$productFactory
}
Then use it like this:
$product=$this>productFactory>create()
$product>loadByAttribute('sku',$sku)
$product=$this>productFactory>create()
$product>load($product>getIdBySku($sku))
1 Actually while this is still working, using load() and collections is the "Magento 1" way, better use the repository
as suggested by @RiccardoT. Fabian Schmengler Apr 17 '16 at 20:46
1 Also, your method will return a Product model, whilst using the Repository will give you a Product data model
( Api/Data/Product), which is a Product model converted into a dumbed-down DTO. Something to consider, as
they're quite different. nevvermind Apr 18 '16 at 0:02
Try this:
/**@var\Magento\Catalog\Model\ProductFactory$productFactory*/
$product=$productFactory>create()
$product>loadByAttribute('sku','mysku')
//$product>load($product>getId())//mayneedtodothistoo,
//see\Magento\Framework\Api\AttributeValueFactory\AbstractModel::loadByAttribute
I need to get the product_id from sku (column of csv) during csv import and save only the product_id..How to achieve?
Sachin S Aug 25 '16 at 9:45