wp-eloquent icon indicating copy to clipboard operation
wp-eloquent copied to clipboard

Working with a clone of $wpdb instance

Open szepeviktor opened this issue 5 years ago • 1 comments

AFAIK when you put $wpdb into $this->db it gets cloned instead of a reference.

What do you think about https://github.com/szepeviktor/debian-server-tools/blob/master/webserver/wordpress/_core-wpdb.php?

szepeviktor avatar Aug 03 '19 21:08 szepeviktor

Please take a look at this. I'm trying to connect to a 2nd database but Eloquent keeps the settings of the "first" connection. Please see the following snippet of one of my classes:

private function connectExternal() {
    global $wpdb;

    $this->dbPrefix = (string) $wpdb->prefix;

    $wpdb = new wpdb(EXT_USER, EXT_PASSWORD, EXT_NAME, EXT_HOST); //EXT_NAME = woop
    $wpdb->prefix = 'nl_';
}

private function disconnectExternal() {
    global $wpdb;

    $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
    $wpdb->prefix = $this->dbPrefix;
}

public function import_dealers() {
    $this->connectExternal();
    $dealers = Migration\InControl\Dealer::with(['address', 'recipients'])->get();
    $this->disconnectExternal();

    $wpDealer = Model\Dealer::all();
}

Results in:

WordPress database error Table 'woop.nl_dealers' doesn't exist

So the second Model should use the DB settings from the config, but uses the first initiated values. In this example the (connectExternal) Migration. So instead of above it should query on:

'845461375_wpdb.wp_dealers'

As @szepeviktor mentioned: it shouldn't be a clone (of the first initiation of the class) but a reference to the super global. OR any other solution.

Can you see to it that we can connect to multiple databases with your class?

BrutusBossNL avatar Oct 30 '19 08:10 BrutusBossNL