Nithin
Nithin

Reputation: 543

Can someone explain this snippet of magento code?

could some one please explain this snippet of magento code found in loadByCustomerId() in the class Mage_Sales_Model_Mysql4_Quote.

$read = $this->_getReadAdapter();
$select = $this->_getLoadSelect('customer_id', $customerId, $quote)
                ->where('is_active=1')
                ->order('updated_at desc')
                ->limit(1);
$data = $read->fetchRow($select);

When i var_dump($data) i see that its an array of customer data. What is model associated with this $data array? Thanks.

Upvotes: 3

Views: 2267

Answers (2)

Alana Storm
Alana Storm

Reputation: 166046

Magento "Models" (meaning the entities that allow you to interact with the database, not general purpose server/domain models) have two layers. The first is the "Model" layer. This contains methods for logical interactive with an model. (get me a customer's address, place the order, etc). The second layer is the "Resource Model" layer. Resource Models handle any interactive with the database (or,more generally, the data-store,or the persistance layer, or etc.).

The way a Resource Model interacts with the database is via adapter objects. One for reading information, another for writing information.

So, you're in the class Mage_Sales_Model_Mysql4_Quote. This is a Resource Model. It's the backend for the Mage_Sales_Model_Quote object, instantiated with

$model = Mage::getModel('sales/quote');

With this line

$read = $this->_getReadAdapter();

you're getting a reference to the model's read adapter. This will let you make queries to the database.

With this line

$select = $this->_getLoadSelect('customer_id', $customerId, $quote)
                ->where('is_active=1')
                ->order('updated_at desc')
                ->limit(1);

You're getting a reference to the SQL statement (also an object) that this Resource Model will use to load a sales/quote object.

//gets a reference
$this->_getLoadSelect('customer_id', $customerId, $quote)

Then, you're calling methods on that object to alter it with additional logic

->where('is_active=1')
->order('updated_at desc')
->limit(1);

In pseudo sql, a query might look like this normally

SELECT * FROM quote_table;

But after you call those methods, the query will look something like

SELECT * FROM quote_table
WHERE is_active = 1
ORDER BY updated_at desc
LIMIT 1;

Finally,

$data = $read->fetchRow($select);

here you're using the read adapter you fetched earlier to make a query into the database for the specific quote item row that your query will fetch.

Upvotes: 5

John Watson
John Watson

Reputation: 2573

_getReadAdapter() gets the read-only database connection. _getLoadSelect creates a select query on the model's (Mage_Sales_Model_Mysql4_Quote) main table. The data returned is just raw data from the SQL query not associated with any particular backend model.

Upvotes: 2

Related Questions