简体   繁体   中英

how to use database transaction for multiple connection in laravel?

we are developing a multi tenant application using 2 separate connections for multiple databases. User model uses main connection and Role uses tenant connection .users table has many to many relationship to roles table with pivot table role_user having columns user_id and role_id .FK user_id references users table from main database. using db transaction on user::create() and $newuser->roles->sync(); throws error. how to implement db transaction in multi-tenant system. Any help is appreciated.

class User extends Authenticatable implements JWTSubject
{   
    use Notifiable;

    //use main connection
    protected $connection = 'main';

     public function roles()
    {
        return $this->belongsToMany('App\Models\Tenant\Role');
    }
}


class Role extends Model
{
     protected $connection = 'tenant';
}

//in UserController.php
 DB::beginTransaction();

        try {
            $newUser = User::create([
                'name' => $request->name,
                'email' =>  $request->email,
                'password' => $request->password
            ]);

            $rolesArray =  $request->roles;
            $newUser->roles()->sync($rolesArray);

           DB::commit();

            return response()->json(['status' => true, 'message' => 'successfull!!']);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['status' => false, 'message' => 'internal Server Error!!']);
        }

Error message : "SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction (SQL: insert into role_user ( role_id , user_id ) values (2, 13))",

You seem to be experiencing the issue described in https://github.com/laravel/framework/issues/23413 .

Unfortunately, there is no trivial "solution" beyond removing the foreign keys, although, I'm exploring workarounds when using PostgreSQL (instead of MySQL/MariaDB) and will update this post if I discover a better approach.

This is something which is going beyond the normal Eloquent use-case, and Eloquent can become really nasty when you are going beyond normal usecases.

To solve this, first you want to create an user on the main database and create a service or repository to create and retrieve the roles on the tennant.

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