Laravel 多对多 - 不同的数据库

Laravel Many-To-Many - Different databases

需要一些关于问题的线索...我正在尝试使用多对多关系从另一个数据库获取数据。

基本上,一个站点可以有多个模板,一个模板可以有多个站点。

网站模型:

class Site extends Model
{
    use HasFactory;

    /**
     * Database Connection Name
     */
    protected $connection = 'hub';

    /**
     * Model Table Name
     */
    protected $table = 'tbl_sites';

    /**
     * Model Primary Key
     */
    protected $primaryKey = 'id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'code', 'name', 'abbreviation', 'address', 'zipcode', 'town', 'geolocation_id', 'gps'
    ];

    /**
     * Returns associated SGC templates
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function sgc_templates()
    {
        return $this->belongsToMany('App\Models\SGC\Contracts\Templates\Template', 'sgc_contracts_templates_hasmany_sites', 'site_id', 'template_id');
    }
}

模板型号:

class Template extends Model
{
    use HasFactory;

    /**
     * Database Connection Name
     */
    protected $connection = 'sgc';

    /**
     * Model Table Name
     */
    protected $table = 'sgc_contracts_templates';

    /**
     * Model Primary Key
     */
    protected $primaryKey = 'id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'description', 'file_name'
    ];

    /**
     * Returns associated sites
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function sites()
    {
        return $this->belongsToMany('App\Models\Hub\Sites\Site', 'sgc_contracts_templates_hasmany_sites', 'template_id', 'site_id');
    }
}

如果我尝试获取与以下网站关联的模板:Site::with('sgc_templates')->find(1),一切正常。

如果我尝试通过以下方式获取与模板关联的网站:Template::with('sites')->find(1),我收到错误消息。基本上是说 pivot table 在站点数据库中不存在。模板和枢轴 table 在 sgc connection/database.

错误是:

Illuminate\Database\QueryException
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'hub.sgc_contracts_templates_hasmany_sites' doesn't exist (SQL: select `tbl_sites`.*, `sgc_contracts_templates_hasmany_sites`.`template_id` as `pivot_template_id`, `sgc_contracts_templates_hasmany_sites`.`site_id` as `pivot_site_id` from `tbl_sites` inner join `sgc_contracts_templates_hasmany_sites` on `tbl_sites`.`id` = `sgc_contracts_templates_hasmany_sites`.`site_id` where `sgc_contracts_templates_hasmany_sites`.`template_id` in (1))

很明显,Template::with('sites')->find(1) 进入了错误的数据库,因为在错误中,'hub.sgc_contracts_templates_hasmany_sites' 应该是 'sgc.sgc_contracts_templates_hasmany_sites'。

有人可以帮我解决这个问题吗? :|

谢谢

找到解决方法。似乎 Many-To-Many 仅在 1 个方向有效 (?)。

Github Issue

Workaround

感谢大家的帮助。

你需要告诉Eloquent你想使用其他数据库,试试这样的事情

return $this->belongsToMany('App\Models\Hub\Sites\Site', 'sgc.sgc_contracts_templates_hasmany_sites', 'template_id', 'site_id');

然后检查它是否尝试查询 sgc db.

如果还是不行,试试这个