题
作为练习的一部分,我试图列出一页上数据库中的所有用户电子邮件。到目前为止,我最接近的是
$user = mage::getModel('customer/customer')->getCollection()->getData();
返回
array
0 =>
array
'entity_id' => string '1' (length=1)
'entity_type_id' => string '1' (length=1)
'attribute_set_id' => string '0' (length=1)
'website_id' => string '1' (length=1)
'email' => string 'john.doe@example.com' (length=20)
'group_id' => string '1' (length=1)
'increment_id' => string '000000001' (length=9)
'store_id' => string '1' (length=1)
'created_at' => string '2007-08-30 23:23:13' (length=19)
'updated_at' => string '2008-08-08 12:28:24' (length=19)
'is_active' => string '1' (length=1)
'disable_auto_group_change' => string '0' (length=1)
1 =>
array
'entity_id' => string '2' (length=1)
'entity_type_id' => string '1' (length=1)
'attribute_set_id' => string '0' (length=1)
'website_id' => string '1' (length=1)
'email' => string 'tony09uk@gmail.com' (length=18)
'group_id' => string '1' (length=1)
'increment_id' => null
'store_id' => string '1' (length=1)
'created_at' => string '2013-07-19 14:31:00' (length=19)
'updated_at' => string '2013-07-19 14:31:00' (length=19)
'is_active' => string '1' (length=1)
'disable_auto_group_change' => string '0' (length=1)
但是我只希望他们的电子邮件被列出,我尝试了魔术获取器和固定器,但没有(或者至少不是我使用的方式)。我也尝试了
$user = mage::getModel('customer/customer')->getCollection()->load();
和
$user = mage::getModel('customer/customer')->getCollection()
->addAttributeToSort('email', 'ASC');
和
$user = mage::getModel('customer/customer')->getCollection()->getEmail()->getData();
和
$user = mage::getModel('customer/customer')->getCollection()->getData();
echo $user->getEmail();
除了其他几种变体外,现在我已经到了我只是随机地遵守他们的希望,我不喜欢这样做。
如何为所有用户显示电子邮件? (我希望我不要远离标记)
解决方案
您实际上几乎在那里,但重要的是要知道发生了什么事。如果您使用 getCollection
方法您实际上是在构建查询。继续尝试以下
$collection = mage::getModel('customer/customer')->getCollection();
var_dump((string)$collection->getSelect());
这将使您回到关注
选择
e
。* 从customer_entity
作为e
在哪里 (e
.entity_type_id
= '1')
这是客户收集的默认查询。您可能会注意到,没有指定字段来检索其检索所有内容。因此,让我们添加一些字段!
$collection = mage::getModel('customer/customer')->getCollection()
->addAttributeToSelect('email')
->addAttributeToFilter('firstname', 'sander')
->addAttributeToSort('email', 'ASC');
var_dump((string)$collection->getSelect());
这将打印以下查询
选择
e
.*,at_firstname
.value
作为firstname
从customer_entity
作为e
内部联接customer_entity_varchar
作为at_firstname
上 (at_firstname
.entity_id
=e
.entity_id
) 和 (at_firstname
.attribute_id
='5')其中(e
.entity_type_id
='1')和(at_firstname.value ='sander')订单e
.
如您所见,Magento构建可以根据添加的属性,选择,订购或您想做的任何事情来纠正查询。查看 Magento Collection Wiki 页面以获取有关收藏的更多信息,因为您可以使用很多选项。
在您的情况下,您只需要指定 addAttributeToSelect
因此,它只能检索该领域。关于非EAV收集的使用 addFieldToSelect
.
$users = mage::getModel('customer/customer')->getCollection()
->addAttributeToSelect('email');
foreach ($users as $user)
var_dump($user->getData());