简体   繁体   中英

Laravel - Spatie Multi-tenancy - Getting tables to adhere to tenant database

I'm using Spatie's mutlti-tenancy package to implement multi-tenancy on my app. I'm using the multiple database approach, and at the moment I'm unsure what should go in my.env file, so I've got DB_DATABASE=landlord in there to point to my landlord database. I then use the DomainTenantFinder and it works quite well. I do have an issue though, usually when I want to indicate a model should use the tenant database connection, I include the following in the model:

use Spatie\Multitenancy\Models\Concerns\UsesTenantConnection;

class MyModel extends Model
{
    use UsesTenantConnection;

But.. I have the issue that when using pivot tables like the one below with the DB class (declared in the same migration where I declare my model's table)

Schema::create('mymodel_othermodel', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('mymodel_id');
        $table->unsignedBigInteger('someother_id');

        $table->foreign('mymodel_id')
            ->references('id')
            ->on('my_models');

        $table->foreign('someother_id')
            ->references('id')
            ->on('some_other_models');
    });

I write to this as follows:

DB::table('mymodel_somemodel')->insert([
        'mymodel_id' => $mymodel->id,
        'someother_id' => $someother->id,
    ]);

Laravel now tries to look for the mymodel_othermodel table on the landlord database instead of on the tenant databse (even though I'm using the right domain). How do I get pivot tables to respect the tenant database when using the DB class??

Also bonus: What should go in my.env file under DB settings when using multi-tenancy? ;)

using the DB Facade you should specify the connection name like so:

DB::connection('tenant')->table('mymodel_othermodel')->....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM