stanhook's avatar

Connecting to a second Local Database

I can connect to a second database, not a problem. But I currently access the other database using:

$excavationsSql = "SELECT tblEU.Site, COUNT(tblEU.EUNum) AS CountOfEUNum
          FROM tblEU
          GROUP BY tblEU.Site
          HAVING  tblEU.Site = :id";

        $excavationsSql = DB::getPdo()->prepare($excavationsSql);
        $excavationsSql->setFetchMode(\PDO::FETCH_OBJ);
        $excavationsSql->execute([
            'id' => $id
        ]);
       $excavations = collect($excavationsSql->fetchAll());

Which works fine. How do I run a similar query but use the other database?

Thanks, Stan

0 likes
3 replies
stanhook's avatar

I seemed to have gotten it. Would this be the best way:

$newDbSql = "SELECT * FROM 'projects' WHERE `post_type` = 'm6_projects'";

        $newDbSql = DB::connection('mysql_second')->getPdo()->prepare($newDbSql);
        $newDbSql->setFetchMode(\PDO::FETCH_OBJ);
        $newDbSql->execute([ ]);
        $newDb = collect($newDbSql->fetchAll());

I get what I need.

Thanks, Stan

jlrdw's avatar

@stanhook for eloquent:

In model

protected $connection = 'some_connection';

Of course in the database config actually set up a second connection.

Please or to participate in this conversation.