Schedule DB table update in multi tenant application
We are using laravel tenancy/multi-tenant for multi tenant support in our application.
We need to schedule a command which updates the table 'XXX' in each tenant.
This is done because we need to prepare data in advance because of loading time issues.
We first followed the explanationof the laravel task scheduling documentation.
But we ran into the problem that the system is in the genreal tenancy database and not in each specific databse.
Did someone need to do a similar task or know how to approach this problem?
$environment = $this->app->make(\Hyn\Tenancy\Environment::class);
// Retrieve your website
// Now switch the environment to a new tenant.
$environment->tenant($website);
foreach (app(WebsiteRepository::class)->query()->get() as $w) {
$tenancy = app(Environment::class);
$tenancy->tenant($w); // switches the tenant and reconfigures the app
$xxx = XXX:where(...);
}
The error trace is:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'tenancy.XXX' doesn't exist (SQL: select * from `XXX` where (`danger_status` = 0 and `text` = and `class` = ok and `1` is null) limit 1)
If I check with app(\Hyn\Tenancy\Environment::class)->tenant() it gives me the tenant connection, but somehow not the right table. Instead of tenancy.XXX there should be thewebsite_ identifier.XXXX
Be wary about switching tenants. It is recommend switching only once during code execution. Use a background job to run mass changes on tenant databases.
@aless55 Do you tried to use background jobs instead?