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 DCommented Apr 1, 2015 at 21:28
1 Answer
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 incraft/app/bootstrap.php
? Commented Apr 2, 2015 at 0:14 -
I wouldn't hack Craft's bootstrap. Just do it from your plugin's init() method?– Brad Bell ♦Commented Apr 2, 2015 at 0:20
-
1I'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'
? Commented Jul 2, 2015 at 10:21 -
1
-
swapping out the class value: DbConnection for CDbConnection fixed that error.– BradCommented Nov 9, 2016 at 17:17