我試圖從產品集合中獲得產品的名稱和價格,為此我創建了一個自定義腳本進行測驗。
$bootstrap = Bootstrap::create(BP, $_SERVER) 。
$objectManager = $bootstrap->getObjectManager()。
$state = $objectManager->get('MagentoFrameworkAppState')。
$state->setAreaCode('adminhtml') 。
$collection = $objectManager->create('MagentoCatalogModelResourceModelProductCollectionFactory')-> create();
try {
echo $collection->addAttributeToSelect(['name','sku'])-> getSelect();
} catch (Exception $exception) {
echo $exception->getMessage()."
"。
}
但是當我運行這個腳本來檢查MySQL查詢時,我得到了下面的輸出:
SELECT `e`.* FROM `catalog_product_entity` as `e`;
我怎樣才能只獲得產品名稱和價格,而不是整個資料呢?
uj5u.com熱心網友回復:
由于你試圖獲得一個產品集合,它將自動獲得主要的產品物體表。它在查詢中至少需要這個表,因為它需要物體Id來與其他表連接,以獲得集合所需的屬性。否則你將無法檢索到你的名字屬性。 請注意,這個表是相當小的,除了sku代碼外,不包括任何其他屬性。
如果你仔細觀察回傳的資料,你會發現它實際上并沒有抓住所有的屬性,但它確實需要主表。
如果你對這兩個欄位有特別的需求,那么最好使用一個自定義查詢,而不是產品集合。
uj5u.com熱心網友回復:
我建議你試試這個
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create()。
$collection->addAttributeToSelect('*'/span>)。
$collection->setPageSize(3); //只取3個產品。
foreach ($productCollection as $product) {
$productPrice = $product->getPrice()。
$productName = $product->getName()。
}
}
uj5u.com熱心網友回復:
試試這個,
namespace BRINDAHelloWorldBlock。
class HelloWorld extends MagentoFrameworkViewElementTemplate
{
protected $productCollectionFactory;
protected $categoryFactory;
public function __construct()
MagentoFrameworkViewElementTemplateContext $context,
MagentoCatalogModelResourceModelProductCollectionFactory $productCollectionFactory。
MagentoCatalogModelCategoryFactory $categoryFactory。
array $data = [] 。
) {
$this-> productCollectionFactory = $productCollectionFactory;
$this-> categoryFactory = $categoryFactory;
parent::__construct($context, $data)。
}
public function getProductCollection()
{
$collection = $this->productCollectionFactory->create()。
$collection->setPageSize(3)。
foreach ($collection as $product)
{
echo "<pre>"/span>;
print_r($product->getPrice())。
print_r($product->getName())。
}
return $collection;
}
uj5u.com熱心網友回復:
<?php
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$productCollection = $objectManager->create('MagentoCatalogModelResourceModelProductCollectionFactory') 。
$collection = $productCollection->create()->addAttributeToSelect('*'/span>)->load();
foreach ($collection as $product) {
echo 'Name = '.$product->getName().'<br> ' ;
echo 'Price = '.$product->getFinalPrice().'<br> ' ;
echo 'Url = '.$product->getProductUrl().'<br> ' ;
echo 'Image = '.$product->getImage().'<br> ' ;
}
?>
試試這個.....
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/320584.html
標籤:
