13

TL;DR: Is there any way in Magento 2 to make the method getTable from a resource collection model to return the same table name for 2 different parameters?

Detailed Explanation
I will start with an example from Magento 1.
Let's say I have a table called module_entiti1_entity2.
I needed to declare this table in my config.xml like this

<module_resource>
    <class>....</class>
    <entities>
         <entity1_entity2>
             <table>module_entiti1_entity2</table>
         </entity1_entity2>
    </entities>
</module_resource>

Then I can get the table name from a resource collection model for example like this:

$collection->getTable('module/entity1_entity2');

But if I want I can use multiple aliases for the same table.
If my config.xml section becomes

<module_resource>
    <class>....</class>
    <entities>
         <entity1_entity2>
             <table>module_entiti1_entity2</table>
         </entity1_entity2>
         <entity2_entity1>
             <table>module_entiti1_entity2</table>
         </entity2_entity1>
    </entities>
</module_resource>

I can retrieve my table in 2 ways:

$collection->getTable('module/entity1_entity2');
$collection->getTable('module/entity2_entity1');

In Magento 2 there is no more table declaration like above.
I can get my table name like this $collection->getTable('module_entity1_entity2').
Is there a way to tell magento that for the parameter module_entity2_entity1 to return the same table name as for the parameter module_entity1_entity2?

3

What you're looking for is setMappedTableName. Call this inside your resource model:

$this->_resources->setMappedTableName('module_entity1_entity1', 'module_entity1_entity2');

You can put this inside a function then call that before calling the getTable method.

Basically, it says that whenever I ask for module_entity1_entity1, give me the module_entity1_entity2 table.

4
  • Thanks for the suggestion, I will try it and come back with the results. By your recommendations, If I use the setMappedTableName in my resource model constructor it should work, right? That one gets called before any other method from the class.
    – Marius
    Jun 24 '15 at 15:15
  • True, I think that's the best place you can put it so it is mapped permanently. Unless you want it to work in specific cases only. Jun 24 '15 at 15:18
  • Hey. It works. It would be nice if I can do this via di.xml. If it's not possible I will implement my own mechanism. But this is what I needed to get started. Thank you.
    – Marius
    Jun 25 '15 at 8:14
  • You're welcome, I'm a fan BTW. It's my pleasure to be of help to you. Jun 25 '15 at 8:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.