php 如何连接到Magento中的数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/788221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:50:35  来源:igfitidea点击:

How to connect to the database in Magento?

phpmagento

提问by Click Upvote

I'm trying to build a simple Magento Module that needs to connect to the database at the start of each page request. All tables need to be accessible to it. I've been pulling my hair out trying to understand how to do it. The best I could figure out was that I need to set this in the config.xmlfile of my module, but exactly what that command is/how it may be used, i haven't been able to figure out.

我正在尝试构建一个简单的 Magento 模块,它需要在每个页面请求开始时连接到数据库。它需要可以访问所有表。我一直在努力了解如何做到这一点。我能想到的最好方法是我需要在config.xml我的模块文件中设置它,但该命令究竟是什么/如何使用它,我一直无法弄清楚。

Can someone please guide me or show me how to accomplish this? If not, would it be too bad a practice to include a custom config.phpfile which connects to the database manually?

有人可以指导我或告诉我如何做到这一点吗?如果没有,包含config.php手动连接到数据库的自定义文件是否太糟糕了?

回答by Rick J

Are you trying to use a resource model or entity ? here is how you can query a table using raw SQL but you need to know the tablename.

您是否尝试使用资源模型或实体?这是使用原始 SQL 查询表的方法,但您需要知道表名。

$w = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $w->query('select entity_id from catalog_product_entity');

if (!$result) {
    return false;
}

$row = $result->fetch(PDO::FETCH_ASSOC);
if (!$row) {
    return false;
}

When trying to all a model you can use

尝试使用所有模型时

$products = Mage::getModel('catalog/product')->getCollection();

$products->addAttributeToFilter('entity_id', array('in' => array(1,2)));

$products->addAttributeToSelect('*');
$products->load();

foreach ($products as $_prod) {
   var_dump($_prod->getData());
}

I use the second method for my custom modules and it has worked out fine for me , hope this answer helps :)

我对我的自定义模块使用了第二种方法,它对我来说效果很好,希望这个答案有帮助:)

回答by StrangeElement

What about objects that do not have addAttributeToFilter? I've been trying for hours to load a role object by its name and nothing works. The only possible method is load, which would work perfectly if not for an unexplicable

没有的对象addAttributeToFilter呢?我一直在尝试按名称加载角色对象数小时,但没有任何效果。唯一可能的方法是加载,如果没有无法解释的情况,它会完美地工作

if (!intval($value) && is_string($value)) {
   $field = 'role_id';
}

in Mage_Admin_Model_Mysql4_Role::load, which only makes it impossible to filter using a string value.

in Mage_Admin_Model_Mysql4_Role::load,这只会使得无法使用字符串值进行过滤。

Magento has a Rube Goldbergarchitecture...

Magento 有一个Rube Goldberg架构...