Currenty I’m working on a webshop using an auction module. This auction module has its own set of entities representing an auction and their bids. The main entity is the ProductAuction model. This model has an relation to the Catalog_Product model of Magento.
Everywhere the collection is loaded the products have to be loaded after the collection of ProductAuctions has been loaded.
Now I have to write some exotic queries to load a specific sets of auctions in combination with category and search queries. Now I first have to load a collection of products belonging to the given category and search query, then load the active auctions belonging to the set of corresponding products.
In some scenarios I can’t reuse the set of loaded products and then have to execute another query to load the products corresponding the auctions.
Worst case I’ll have to execute three big queries and process the resultsets which should be possible in one query.
Is it possible in Magento to load relating entities within a collection, just like any decent ORM would do with One-2-One, Many-2-One and other relations?
I haven’t found any example of this, but I can’t imagine this isn’t possible in Magento.
Thanks for any help on this.
== EDIT ==
A bit of example code to show what I’m doing at the moment:
/**
* Build the correct query to load the product collection for
* either the search result page or the catalog overview page
*/
private function buildProductCollectionQuery() {
/**
* @var Mage_CatalogSearch_Model_Query
*/
$searchQuery = Mage::helper('catalogsearch')->getQuery();
$store_id = Mage::app()->getStore()->getId();
$productIds = Mage::helper('auction')->getProductAuctionIds($store_id);
$IDs = array();
$productIds = array();
$collection = Mage::getModel('auction/productauction')
->getCollection()
->addFieldToFilter(
'status', array('in' => array(4))
);
if (count($collection)) {
foreach ($collection as $item) {
$IDs[] = $item->getProductId();
}
}
$collection = Mage::getResourceModel('catalog/product_collection')
->addFieldToFilter('entity_id',array('in'=> $IDs ))
->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes())
->addMinimalPrice()
->addTaxPercents()
->addStoreFilter();
if( $searchQuery != null ) {
$collection->addAttributeToFilter(array(
array('attribute' => 'name', 'like'=>'%' . $searchQuery->getQueryText() . '%'),
array('attribute' => 'description', 'like'=>'%' . $searchQuery->getQueryText() . '%')
)
);
// @TODO This should be done via the Request object, but the object doesn't see the cat parameter
if( isset($_GET['cat']) ) {
$collection->addCategoryFilter(Mage::getModel('catalog/category')->load($_GET['cat']) );
}
}
return $collection;
}
Managed to come up with a solution. I now use the following code to get all the information I need. Still I’m surprised it is so hard to create instances of relating objects like any normal ORM would do. But perhaps I am expecting too much of Magento..
Anyway, this is the code I use now: