【问题标题】:Bind Laravel table to other database connection将 Laravel 表绑定到其他数据库连接
【发布时间】:2020-01-29 00:55:19
【问题描述】:

我发现将一个关系表绑定到我的第二个数据库有些困难。

在“db_main”中,我有表格,其中包含每个对象的基本详细信息,而不是其他表格:“db_site1”、“db_site2”等,在这些表格中我保存了有关相同对象的详细信息。

一切都在使用该架构找到,除了我有关系表(bookmaker_games)的一种情况,它必须只在“db_main”上。该表保存了博彩公司和游戏之间的关系。

在我的网站1上,我想列出以下型号的博彩公司的游戏:

class Bookmaker extends Model {

    public function games() {
        // here the database is "db_site1"
        return $this->belongsToMany('App\Models\Game', 'bookmaker_games', 'bookmaker_id', 'game_id');

    }

}

class Game extends Model {

    public function bookmakers() {
        // here the database is "db_site1"
        return $this->belongsToMany('App\Models\Bookmaker', 'bookmaker_games', 'game_id', 'bookmaker_id');

    }
}

class BookmakerGame extends Model {

    protected $connection = 'db_main';

}

当我尝试返回所有游戏时,它认为“bookmaker_games”-table 在数据库“db_site1”上,这是错误的。

告诉该关系查看正确数据库的最佳方法是什么?

【问题讨论】:

  • 类 BookmakerGame 应该扩展 Illuminate\Database\Eloquent\Relations\Pivot
  • 我试过了,但还是出现同样的错误:SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db_site1.bookmaker_games' doesn't exis

标签: laravel eloquent relationship


【解决方案1】:

将BookmakerGame 声明为Illuminate\Database\Eloquent\Relations\Pivot 的子类

然后定义要使用它的关系。

为连接名称添加前缀

//...
use Illuminate\Database\Eloquent\Relations\Pivot;

class Bookmaker extends Model {

    public function games() {
        // here the database is "db_site1"
        return $this->belongsToMany(
           'App\Models\Game', 'db_main.bookmaker_games', 'bookmaker_id', 'game_id')
            ->using('App\Models\BookmakerGame');
    }
}

class Game extends Model {

    public function bookmakers() {
        // here the database is "db_site1"
        return $this->belongsToMany(
           'App\Models\Bookmaker', 'db_main.bookmaker_games', 'game_id', 'bookmaker_id')
            ->using('App\Models\BookmakerGame');

    }
}

class BookmakerGame extends Pivot {
    protected $connection = 'db_main';
}

使用枢轴的类路径


use Illuminate\Database\Eloquent\Relations\Pivot;

class Bookmaker extends Model {

    public function games() {
        // here the database is "db_site1"
        return $this->belongsToMany(
           'App\Models\Game', 'App\Models\BookmakerGame', 'bookmaker_id', 'game_id');
    }
}

class Game extends Model {

    public function bookmakers() {
        // here the database is "db_site1"
        return $this->belongsToMany(
           'App\Models\Bookmaker', 'App\Models\BookmakerGame', 'game_id', 'bookmaker_id');

    }
}

class BookmakerGame extends Pivot {
    protected $connection = 'db_main';
    protected $table = 'bookmaker_games';
}

【讨论】:

  • 还是不行。 BookmakerGame 仍未在正确的数据库中搜索 :(
  • 我建议将连接名称添加到表的前缀或使用BookmakerGame的类路径
猜你喜欢
  • 2013-06-28
  • 2015-02-17
  • 2017-12-30
  • 1970-01-01
  • 2013-02-19
  • 2017-04-11
  • 1970-01-01
  • 2016-01-21
  • 2021-01-30
相关资源
最近更新 更多