Changing model’s table from the controller

For one reason, or another you might wish to change your Model’s table on the fly…

It would seem that it should be quite easy to do with:


$this->Company->useTable = 'another_company_table';

…but it’s not going to work…

Instead, in your controller, use:


$this->Company->table = 'another_company_table';

I haven’t checked to see why this works the way it does, so if someone has an explanation, I’ll gladly update the post with your insight.

P.S. Phally pointed out that it is better is use the wrapper for setting the table variable (always better than setting vars directly), like so: $this->Company->setSource('another_company_table');

11 thoughts on “Changing model’s table from the controller

  1. I used this and it works, it is probably a wrapper:

    $this->Company->setSource('another_company_table');

    I got it from AD7six.

  2. @keymaster

    I would not, but there are case where someone would… Perhaps based on the logged in user (tracking).
    Or if you have a middle-tier system that requires dynamic table switching, there are certain scenarios where this could be useful.

    Just showing the available option, how it’s used… well that’s, up to the developer.

  3. @keymaster

    I used it to get data from a remote database where the tablename came from the local database. So I had a Remote model which changes tablename.

  4. For a completely dynmic table with an unusual table name (eg. ‘results_1’) I found it to be working only when setting both properties.

    $this->Company->useTable = ‘another_company_table’;
    $this->Company->table = ‘another_company_table’;

    But then it worked even inside the model!

    Thank you for this hint – will save lots of time for the future!

  5. thanks teknoid

    this is what i need

    i need a code that can change table for my multilanguage site

    example

    en_contents for english content
    nl_content for dutch content

    but only use one model


    class Contents extends AppModel
    {
    $useTable = "en_contents"; //for default language
    }

    and for controller


    class ContentsController extends AppController
    {

    var $use = array('Content');

    function get($lang)
    {

    if($lang == 'nl') :

    $this->Content->setSource('nl_contents');

    endif;

    }
    }

  6. @empe

    Cool, thanks for sharing… have you tried the translate behavior, seems like it would do what you are after more efficiently. Unless you have a legacy DB to work with.

Leave a comment