What classes can I use to directly manipulate Magento database tables? I have created a table in the database and would like to be able to insert/update rows in it directly, without having to define a model class, etc. It seems that Magento\Framework\Model\ResourceModel\Db\AbstractDb has the functionality I need, but I'm not sure if I should be using an abstract class directly. Are there any concrete implementations of the class that are designed to be used for my purpose?
- 17,341
- 5
- 60
- 141
- 493
- 2
- 9
- 16
1 Answers
Per the comments, your specific situation is best accomplished in Magento 2 via Extension Attributes. Extension Attributes are the M2 way of adding custom data fields to existing models. In the process, you get out-of-box support for your new attribute in internal and external APIs (and IDE autocompletion).
Create your custom schema (table with the primary key and your custom data columns), then define the extension attribute to join your table. You'll still need to handle saving yourself, via plugins.
See the official documentation on extension attributes here: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/attributes.html
Also see this discussion on implementing an extension attribute in practice, including examples: https://magento.stackexchange.com/a/92054/1905
To answer to your original question: Yes, it is still possible to directly query the database. You should not do this unless absolutely necessary. If you are working with a model, follow best practices and use the ORM layer (the model, resource model, and collection). Laziness or ignorance is not an excuse. Learn and use Magento's architecture the way it's meant to be; you'll save a lot of headaches and possible security problems in the process. If you don't know how it works, read Alan Storm's explanation.
With that disclaimer out of the way: To perform a manual query, you want to use dependency injection to get an instance of \Magento\Framework\App\Resource $resource in your class. Once you have that, $connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION); will give you a database connection.
Note that this connection is an instance of \Magento\Framework\DB\Adapter\Pdo\Mysql. As of version 2.1, it's still built on Zend_Db, so the methods available from here are very similar to what you would have on Magento 1.
Also see this discussion for an example on injecting and using this. https://magento.stackexchange.com/a/88129/1905
- 12,271
- 7
- 47
- 54
sales_ordertable, so I thought that the two obvious options I had were to either add a column on thesales_ordertable directly which means I also have to modifyMagento\Sales\Api\Data\OrderInterfaceclass, or I could create table mapping order id to status. – b_pcakes Jun 15 '16 at 19:22