0

I am just using Laravel whereRelation. It runs smooth and as expected if the relations between 2 tables is in the same database (DB_A). The problem is when I have to use 2 databases (DB_A and DB_B). In the model relationship I put the connections and there is no problem

// Model user DB_A

protected $connection = 'mysql';

public function address()
{
    return $this->hasOne(Address::class, 'id_user');
}
// Model address DB_B

protected $connection = 'mysql2';
protected $table = 'address';

public function user()
{
    return $this->belongsTo(User::class, 'id_user');
}

In the query I want to get all the relationship between those 2 tables. The query like:

$data = User::with('address')->reorder('id', 'desc');
$data = $data->whereRelation('address', 'status', '=', 'verified');

I got the error say that table address doesn't exist in DB_A which is belong to DB_B. If i remove the line whereRelation takeplace it doesn't give any errors. How to handle or specify the database name and table name in whereRelation?

EDIT: Both DB_A and DB_B is in different Host.

far1023
  • 113
  • 10
  • Does this answer your question? [laravel BelongsTo relationship with different databases not working](https://stackoverflow.com/questions/32422593/laravel-belongsto-relationship-with-different-databases-not-working) – ManojKiran A Nov 11 '21 at 09:18
  • I forgot to mention that the second connection is on another machine. Both db is not in the same machine. I kept getting error the table doesn't exist, even when I set the table name or connection multiple times. Is it possible to make relation with multiple db with different server machine? – far1023 Nov 11 '21 at 13:45
  • Do you mean different host ? – ManojKiran A Nov 11 '21 at 13:50
  • yaa different host – far1023 Nov 11 '21 at 14:11

1 Answers1

0

Try it will hopefully work

Model address DB_B

 class User  extends Eloquent {
    
       // *******default connection************
    
       public function address() {
           return $this->setConnection('mysql')->belongsTo(Address::class, 'id_user');
       }
    }

Model address DB_B

class Address extends Eloquent {

   // *******default connection************

   public function user() {
       return $this->setConnection('mysql2')->belongsTo(User::class, 'id_user');
   }
}
  • I've tried it before. Not giving any progress for now. And I updated my question. `DB_A` and `DB_B` is on different Host – far1023 Nov 11 '21 at 13:48