I'm trying to setup a polymorphic relationship on multiple database on connection.
Let's say I have
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()?
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() :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With