orchestral / tenanti

[Package] Multi-tenant Database Schema Manager for Laravel
MIT License
588 stars 52 forks source link

Multiple Database - Set connection using ID instead of model #59

Closed rafaelrenanpacheco closed 6 years ago

rafaelrenanpacheco commented 6 years ago

Hi there!

Would be possible to Tenanti::driver('company')->asDefaultConnection(Model $entity, $database) have an alternative to accept an ID instead of a model in the first parameter?

In my app the tenancy is around the user's company, so I have multiple databases for the companies, and I need to connect it using asDefaultConnection passing the user's company as the first parameter. This works just fine, the problem here is that two SQLs are firing up upon each request.

The first one is from laravel passport, to load which user is logged in. The second one is to get the company model from that user. This is the code that fires the second query to fetch the company model:

Tenanti::driver('company')
       ->asDefaultConnection($request->user()->company, 'company_{id}');

Since the user() model is already retrieved, and user belongs to a company, the user model has directly access to the company_id, which is all I need to define which tenancy database to use. So, something like this would avoid this unnecessary SQL to fetch the company model:

Tenanti::driver('company')
       ->asDefaultConnectionById($request->user()->company_id, 'company_{id}');

Digging in the Operation.php file, asDefaultConnection() and asConnection() are using the tenancy model in a way that I don't know how to make this asDefaultConnectionById() alternative.

Any tips on how to code this alternative connection that does not need a model?

Using Laravel 5.5 and orchestral/tenanti 3.5.x@dev.

crynobone commented 6 years ago

Not possible, feel free to build your own database connection resolver to archive the same result.

rafaelrenanpacheco commented 6 years ago

I know that is not possible, I just asked for some tip on how to code this alternative because asDefaultConnection and asConnection are heavily using models.

I'll try something here and PR if I succeed, thanks!