在一个问题上需要一些启发...我正在尝试使用多对多关系从另一个数据库获取数据。
基本上,一个站点可以有多个模板,一个模板可以有多个站点。
站点模型:
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)获取与模板相关联的站点,则会出现错误。基本上说,数据透视表不存在于站点数据库中。模板和数据透视表在sgc连接/数据库上。
错误是:
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))很明显,模板指向了错误的数据库,因为在出现错误时,'hub.sgc_contracts_templates_hasmany_sites‘应该是’sgc.sgc_contracts_ Template::with('sites')->find(1) _hasmany_site‘。
有人能帮我一下吗?:|
谢谢
发布于 2020-11-04 22:30:25
发布于 2020-11-05 08:33:19
你需要告诉Eloquent你想使用其他的db,试试下面这样的方法
return $this->belongsToMany('App\Models\Hub\Sites\Site', 'sgc.sgc_contracts_templates_hasmany_sites', 'template_id', 'site_id');然后检查它是否试图查询sgc db。
如果仍然无济于事,试试这个https://stackoverflow.com/a/60060726/7892040。
https://stackoverflow.com/questions/64680691
复制相似问题