Answers:
要获取具有状态启用和可见性的产品集合:
您必须将以下代码保存在阻止文件中。
protected $productCollectionFactory;
protected $productVisibility;
protected $productStatus;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
\Magento\Catalog\Model\Product\Visibility $productVisibility,
array $data = []
)
{
$this->productCollectionFactory = $productCollectionFactory;
$this->productStatus = $productStatus;
$this->productVisibility = $productVisibility;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()]);
$collection->setVisibility($this->productVisibility->getVisibleInSiteIds());
return $collection;
}
上面的代码可用于以下可见性类型:
SearchCriteriaBuilder
使用时ProductRepositoryInterface
?(见magento.stackexchange.com/a/84347/60128。 )
这应该为您工作:
$collection = $this->collectionFactory->create();
$collection->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()]);
$collection->setVisibility($this->productVisibility->getVisibleInSiteIds());
使用的类是:
/**
* @var \Magento\Catalog\Model\Resource\Product\CollectionFactory
*/
protected $collectionFactory;
/**
* @var \Magento\Catalog\Model\Product\Attribute\Source\Status
*/
protected $productStatus;
/**
* @var \Magento\Catalog\Model\Product\Visibility
*/
protected $productVisibility;
复查这些类以检查其他方法以获得可能的状态或可见性值。
但是,据我所知,Magento 2建议回顾存储库的概念,建议使用存储库访问产品数据而不是使用集合。例如:
$searchCriteria = $this->searchCriteriaBuilder->create();
$products = $this->productRepository->getList($searchCriteria)->getItems();
具有状态启用和可见性的产品收集:
您可以尝试以下代码
protected $productCollectionFactory;
protected $productVisibility;
protected $productStatus;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
\Magento\Catalog\Model\Product\Visibility $productVisibility,
array $data = []
)
{
$this->productCollectionFactory = $productCollectionFactory;
$this->productStatus = $productStatus;
$this->productVisibility = $productVisibility;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()]);
$collection->setVisibility($this->productVisibility->getVisibleInSiteIds());
return $collection;
}
该代码适用于可见性类型,例如:
VISIBILITY_IN_SEARCH
VISIBILITY_IN_CATALOG
VISIBILITY_BOTH