I am working with the collection from a module trying to return specific information. The database has several columns but I only want 2: "region_id" & "default_name". But, every time I run this function, returns nothing and when I do $CollectionOrigin->getSelect->__toString()
I get the correct resulting SQL command, which returns the correct values when run in the Database.
here's my function, can someone tell me what I'm missing
-
Your module have one table only and you are using that model only?– Dhiren VasoyaFeb 7, 2022 at 9:34
-
@DhirenVasoya i checked the module this originated from, and I'm pretty sure its more than 1 table (3 I think) however, the getSelect() command returns an SQL, that when run on the database, returns the correct results from only ONE of the 3 tables.– ZyzzxFeb 7, 2022 at 10:27
-
My Question is that, you need to use proper Model where those 2 column are available, so you get your desire result.– Dhiren VasoyaFeb 7, 2022 at 11:10
-
@DhirenVasoya if it was the wrong model wouldn't the SQL generated be for the wrong table? and NOT give me my desired results?– ZyzzxFeb 7, 2022 at 11:13
-
Can you try with the below code to print the collection data before for-each statement? var_dump($regionCollectionOrigin->getData();)exit;– Jitendra PatelFeb 7, 2022 at 13:04
3 Answers
1] Fetching collection with single table use the below code.
$collection = $this->reservationFactory->create()->getCollection();
$collection->addFieldToFilter('quote_id',$quote_id);
2] Fetching product layer collection with EAV tables use the below code.
$collection = $layer->getProductCollection();
$collection->addAttributeToFilter('status',1);
3] I assume you have a single table then can you modify the code as below.
$id = 1234;
$regionCollectionOrigin = $this->_regionFactory->create()->getCollection();
$regionCollectionOrigin->addFieldToFilter('region_id',$id);
var_dump($regionCollectionOrigin->getData();)exit;
Use this code to get the default name and region id
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$region = $objectManager->create('Magento\Directory\Model\Region')
->loadByCode('CA', 'US');
echo "<pre>";
print_r($region->getData());
Output:
Array
(
[region_id] => 12
[country_id] => US
[code] => CA
[default_name] => California
[name] => California
)
-
-
I have posted another answer please check that and I am sure this can help you.– ARJUNFeb 14, 2022 at 4:28
Get the default name using region id
<?php
use Magento\Directory\Model\RegionFactory;
class Save extends \Magento\Framework\App\Action\Action
{
protected $regionFactory;
public function __construct(
RegionFactory $regionFactory
){
$this->regionFactory = $regionFactory;
}
$regionId = '1';
public function getRegionData( $regionId ){
$region = $this->regionFactory->create()->load($regionId);
echo "<pre>";
print_r($region->getData());
}
}
OUTPUT
Array
(
[region_id] => 1
[country_id] => US
[code] => AL
[default_name] => Alabama
[name] => Alabama
)