I'm trying to integrate a new Laravel app with an legacy application. That's why I'm in need to use two databases/connections.
Specified my default connection in app/config/database
'default' => 'connection-one',
A normal one-to-one relation across two databases is working as expected.
But when I'm trying to use a many-to-many relationship Laravel is using the wrong database.
models/Member.php
class Member extends Eloquent
{
protected $connection = 'connection-two';
protected $primaryKey = 'id_member';
protected $table = 'legacy_members_table';
public function topics()
{
return $this-->belongsToMany('Topic');
}
}
models/Topic.php
class Topic extends Eloquent
{
protected $primaryKey = 'token';
public function members()
{
return $this->belongsToMany('Member');
}
}
Laravel is searching for the correct pivot table member_topic
but does this in the old databse with connection-two
and not in the new database with connection-one
Is there a way to achieve this ?
The only solution currently on my mind is to use a view in the 'new' database that will use/mimic the data from the table in the old database.
Using 'legacy_db' as an example of the actual name for your old database, would this work?
class Topic extends Eloquent
{
protected $primaryKey = 'token';
public function members()
{
$relation = $this->belongsToMany('Member');
$relation->table = 'legacy_db.legacy_members_table';
return $relation;
}
}
Take a look at this to clarify http://fideloper.com/laravel-multiple-database-connections
OK, I figured it out (after some sleep). Thanks @thevelement to point me into the right direction.
Simply specify [database].[table_name] as the second argument of the relation
class Topic extends Eloquent
{
protected $primaryKey = 'token';
public function members()
{
retrun $this->belongsToMany('Member','legacy_db.legacy_members_table');
}
}
Was this really resolved? Are you truly using two distinct servers or just two different schemas?
I am still unable to do this across two server connections (vs two schemas).
You can do it across multiple server connections with Eloquent. It can get tricky when trying to query through Fluent.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community