0

My application has to use two database connections, called mysql1 and mysql2. The User model is on the first connection and the Department model is on the second one.

There's a relationship between the two, a Department belongsToMany Users. The relationship uses the department_user pivot table that is stored on the mysql2 database.

This works great, except when it comes to testing. I'm using PHPUnit and setting the DB_DRIVER to sqlite and the DB_DATABASE to :memory: so that the test runs faster and don't hit the actual MySQL databases.

How can I make the in-memory databases work with multiple connections? Is there a way to give each of them a unique name?

The error the phpunit returns is table not found, meaning it is unable to connect second database.

user3805033
  • 157
  • 1
  • 3
  • Possible duplicate of [Laravel multiple databases PHPUnit](https://stackoverflow.com/questions/44392039/laravel-multiple-databases-phpunit) – Douwe de Haan Jun 05 '18 at 21:11

1 Answers1

0

I've run into some similar issues. It may be possible, but I ultimately scrapped using :memory: in favor of a local file for my SQLite databases instead. Then I'd have the opportunity to give them unique names, as you suggest.

Also, in order to give each database an awareness of the other for the sake of your pivot tables, you're going to have to make your test execute ATTACH DATABASE '$database' AS $name on the one the query is going to originate with. And make sure you're not executing that statement inside of a transaction, or it wont work.

Check out my answer here: belongsToMany relationship in Laravel across multiple databases. I think it's along the lines of what you're looking for.

kmuenkel
  • 2,659
  • 1
  • 19
  • 20