laravel BelongsTo relationship with different databases not working

后端 未结 9 937
無奈伤痛
無奈伤痛 2020-12-06 00:25

I\'ve seen in several places to \"stay away\" from this, but alas - this is how my DB is built:

class Album extends Eloquent {

   // default connection

            


        
9条回答
  •  Happy的楠姐
    2020-12-06 00:26

    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();
        }
    }
    
    class MyModel extends Model
    {
        public function myOtherModel()
        {
            return $this->belongsTo(MyOtherDBModel::class, 'field', 'field');
        }
    }
    

    Now i can call

    $query = MyModel::whereHas('myOtherModel');
    

提交回复
热议问题