8

I'm writing another plugin for my craft app, this time I'm attempting to reuse a MySQL table that's used by other applications as well. I've a class extending the BaseRecord, and getTableName() will return differentdb.tablename. Does Craft handle this, or do I have to make a copy of that table in the craft database? (MySQL permissions for the craft user already give it read access to that database)

  • Great question, I've wondered this myself. – Lindsey D Apr 1 '15 at 21:28
8

Have you tried it? I'm pretty sure that's not going to work as Active Record is tied to the db connection in craft/config/db.php hanging off of craft()->db.

You should be able to pull it off with a plugin that instantiates its own DbConnection, though and uses Query Builder instead of Active Record. Completely untested, but something like this:

$otherDbConnection =  Craft::createComponent(array(
    'emulatePrepare'    => true,
    'charset'           => 'utf8',
    'tablePrefix'       => 'craft_',
    'class'             => 'Craft\DbConnection',
    'autoConnect'       => true,
));

$otherDbConnection->connectionString = 'mysql:host=localhost;dbname=otherdb;port=3306';
$otherDbConnection->username = $userName;
$otherDbConnection->password = $password;

From there you can do $otherDbConnection->createCommand() and grab all of the data you want from the other database. It's up to you how you'd merge that in with data from your existing database.

If you wanted to get fancy and access the database in other files/places in code, you could do:

craft()->setComponent('otherDb', $otherDbConnection);

And access the other database via: craft()->otherDb->createCommand().

  • Hey! Thanks for this. I was in a meeting so it took a while to acknowledge. It turns out I'd like to do it the fancy way, so I've put it a config/db.php in my plugin folder. Is it possible to tell Craft to bootstrap my plugin by loading this file first, or do I have to hack it by hardcoding it in craft/app/bootstrap.php? – charmeleon Apr 2 '15 at 0:14
  • I wouldn't hack Craft's bootstrap. Just do it from your plugin's init() method? – Brad Bell Apr 2 '15 at 0:20
  • 1
    I'm trying to use code like that above, but get Fatal error: Class 'DbConnection' not found in /var/www/mydomain.org.uk/craft/app/framework/YiiBase.php on line 213. I'm guessing that 'DbConnection' should be 'CDbConnection'? – Phil Gyford Jul 2 '15 at 10:21
  • 1
    Or Craft\DbConnection. – Brad Bell Jul 2 '15 at 16:45
  • swapping out the class value: DbConnection for CDbConnection fixed that error. – Brad Nov 9 '16 at 17:17

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.