1

通过参考 SQL 了解 Magento 模型:

  1. select * from user_devices where user_id = 1
  2. select * from user_devices where device_id = 3

我如何使用我的 magento 模型执行相同的操作?getModel("module/userdevice")

另外,我怎样才能找到每个查询的行数

以下问题已在此线程中得到解答。

How to perform a where clause ?
How to retrieve the size of the result set ?
How to retrieve the first item in the result set ?
How to paginate the result set ? (limit)
How to name the model ?
4

1 回答 1

3

你指的是集合

给你一些参考:

  1. http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-5-magento-models-and-orm-b​​asics
  2. http://alanstorm.com/magento_collections
  3. http://www.magentocommerce.com/wiki/1_-_installation_and_configuration/using_collections_in_magento
  4. lib/varien/data/collection/db.php 和 lib/varien/data/collection.php

因此,假设您的模块设置正确,您将使用集合来检索模型类型的多个对象。

语法是:

$yourCollection = Mage::getModel('module/userdevice')->getCollection()

Magento 为开发人员提供了一些很棒的功能来使用集合。所以你上面的例子很容易实现:

$yourCollection = Mage::getModel('module/userdevice')->getCollection()
    ->addFieldToFilter('user_id', 1)
    ->addFieldToFilter('device_id', 3);

您可以获得返回的对象数:

$yourCollection->count() 或简单地 count($yourCollection)

编辑

回答评论中提出的问题:“如果我不需要一个集合而只需要一个特定的对象怎么办

这取决于您是否仍需要满足原始问题中的两个条件,或者您是否知道要加载的对象的 ID。

如果您知道对象的 id,那么只需:

Mage::getModel('module/userdevice')->load($objectId);

但如果您仍希望基于这两个属性加载:

user_id = 1
device_id = 3

那么您仍然会使用集合,但只需返回第一个对象(假设只有一个对象只能同时满足两个条件)。

为了重用,将此逻辑包装在一个方法中并放置在您的模型中:

public function loadByUserDevice($userId, $deviceId)
{
    $collection = $this->getResourceCollection()
        ->addFieldToFilter('user_id', $userId)
        ->addFieldToFilter('device_id', $deviceId)
        ->setCurPage(1)
        ->setPageSize(1)
    ;

    foreach ($collection as $obj) {
        return $obj;
    }
    return false;
}

你可以这样称呼它:

$userId = 1;
$deviceId = 3;
Mage::getModel('module/userdevice')->loadByUserDevice($userId, $deviceId);

笔记:

您可以将 loadByUserDevice 缩短为以下内容,但如果找不到对象,您将无法获得 false 返回值的好处:

public function loadByUserDevice($userId, $deviceId)
{
    $collection = $this->getResourceCollection()
        ->addFieldToFilter('user_id', $userId)
        ->addFieldToFilter('device_id', $deviceId)
    ;

    return $collection->getFirstItem();
}
于 2012-06-23T12:00:27.460 回答