0

I am trying to make a polymorphic relationship between two database tables.

database1: SaleReport database2: ThreadConnection

under SaleReport on database1

public function relates(){
    return $this->morphMany(ThreadConnection::class, 'relation');
}

on ThreadConnection at database2

public function relation(){
    return $this->morphTo();
}

But when i try to get the relation like

$salereport = App\SaleReport::find(1);
$salereport->relates


Illuminate/Database/QueryException with message 'SQLSTATE[42S02]: 
Base table or view not found: 1146 Table 'database1.thread_connections'
doesn't exist (SQL: select * from `thread_connections` where 
`thread_connections`.`relation_id` = 484694 and 
`thread_connections`.`relation_id` is not null and 
`thread_connections`.`relation_type` = App/SaleReport)'

I have also tried to define the database connection into the ThreadConnection

$this->setConnection('database2')->morphTo();

But that doesn't worked either!

Any suggestion would be appriciate

koalaok
  • 5,075
  • 11
  • 47
  • 91
Shah
  • 33
  • 5
  • Did you try to set protected $connection = 'database2'; in ThreadConnection model? – koalaok May 29 '18 at 14:27
  • I think it's already been answered here what you're looking for: https://stackoverflow.com/questions/25142968/belongstomany-relationship-in-laravel-across-multiple-databases – koalaok May 29 '18 at 14:54
  • Hi @koalaok, Thanks yes I have done that added the protected $connection = 'db1/db2' in both the model belongs to the databasaes, and the table names protected $table = 'table_names' and that worked like a charm, it was really good that it's that easy to make a relation between two databases with polymorphic relation. – Shah May 31 '18 at 07:45

1 Answers1

0

As stated previously in my comment,

Reading the Error:

Base table or view not found: 1146 Table 'database1.thread_connections'

Meaning Laravel is looking in database1 connection for model ThreadConnection (database1 should be the default connection, if model refers to another connection it should be set explicitly)

Adding in ThreadConnection:

 protected $connection = 'database2';

Will solve the issue.

koalaok
  • 5,075
  • 11
  • 47
  • 91