laravel BelongsTo relationship with different databases not working
Solution for laravel v5.7 and above
class Album extends Eloquent {
// default connection
public function genre() {
return $this->setConnection('Resources')->belongsTo('genre');
}
...
}
This is the way it worked for me:
In my .env and config/database.php i have defined my other connection => How to use multiple databases in Laravel
I updated my model this way:
class MyOtherDBModel extends Model
{
protected $table = 'tablename';
protected $connection = 'mysql2';
public function __construct(array $attributes = [])
{
$this->table = env('DB_DATABASE_2').'.'.$this->table;
parent::__construct($attributes);
}
}
class MyModel extends Model
{
public function myOtherModel()
{
return $this->belongsTo(MyOtherDBModel::class, 'field', 'field');
}
}
Now i can call
$query = MyModel::whereHas('myOtherModel');