Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Polymorphic in Multiple Connection

I'm trying to setup a polymorphic relationship on multiple database on connection.

Let's say I have

  • Database A, Table users (id, email, password, userable_id, userable_type)
  • Database B, Table companies (id, name, address, phone)

On each User and Company model, I also set each connection:

/* Database A */
protected $connection = 'database_a';

/* Database B */
protected $connection = 'database_b';

And for the relationship

/* Database A (User model) */
public function userable()
{
    return $this->morphTo();
}

/* Database B (Company Model) */
public function user()
{
    return $this->morphMany('user','userable');
}

And in my AppServiceProvider.php, I morphMap the user and vendor model:

Relation::morphMap([
    'user' => \App\Models\V1\Shared\User::class,
    'vendor' => \App\Models\V1\Training\Vendor::class       
]);

This code will not work unless I set the userable relationship with connection:

public function userable()
{
    return $this->setConnection('database_b')->morphTo();
}

In case, I want to add more user type and I have to use the new database, How do I use appropriate database/How do I make laravel to detect the connection automatically in morphTo without having to use setConnection()?

like image 255
Yansen Tan Avatar asked Jun 02 '16 02:06

Yansen Tan


1 Answers

This is much late but I have faced recently the same problem, I am now using Laravel 5.5 and there I only had to use

protected $connection = 'db_names' 

for both the models belonging to different databases - that actually worked like a charm.

I didn't have to use

$this->setConnection('database_b')->morphTo(), I just used $this->morphTo() :)
like image 81
Shamsul Alam Avatar answered Oct 17 '22 00:10

Shamsul Alam