通过与不同服务器的多个数据库连接访问多对多关系数据
我正在使用不同服务器上的多个数据库连接.即host1
和host2
.我的默认数据库连接为host2.我的项目有两个表. users
在主机1上存在,而 tasks
在主机2上存在.
I'm working with multiple database connection on different servers. i.e, host1
and host2
. My default database connection is host2. My project have two tables. users
exists on host1 and tasks
exists on host2.
两个表上都有一个many to many
关系.与此关系的数据透视表是 task_users
,该数据存在于host2 .
There is a many to many
relationship on both tables. Pivot table for this relationship is task_users
which exists on host2.
我的模型文件在这里.
User.php
class User extends Authenticatable
{
protected $connection = 'host1';
public function tasks()
{
return $this->belongsToMany(Task::class, 'task_users', 'user_id', 'task_id');
}
}
Task.php
class Task extends Model
{
protected $connection = 'host2';
public function users()
{
return $this->belongsToMany(User::class, 'task_users', 'task_id', 'user_id');
}
}
使用此模型文件时,当我试图吸引任务的用户时,会出现此错误.
With this model files, when I'm trying to get users of a task, I'm getting this error.
找不到基本表或视图:1146表'database_hosted_on_host1_server.task_users'不存在.
Base table or view not found: 1146 Table 'database_hosted_on_host1_server.task_users' doesn't exist.
这是我的控制器代码
$task = Task::find($taskId);
dd($task->users->toArray());
我也尝试过此也.但是只有两个数据库都在同一服务器上时,它才起作用.
I have also tried this too. But it works only if both database are on same server.
I have also tried Defining Custom Intermediate Table Models from laravel documentation. But still getting error. I think I'm doing some mistake in pivot class.
这是我的代码.
Task.php
class Task extend Model
{
protected $connection = 'host2';
public function users()
{
return $this->belongsToMany(User::class)->using(TaskUser::class);
}
}
TaskUser.php
使用Illuminate \ Database \ Eloquent \ Relations \ Pivot;
use Illuminate\Database\Eloquent\Relations\Pivot;
class TaskUser extends Pivot
{
protected $connection = 'host2';
protected $table = 'task_users';
}
使用此代码,当我试图吸引任务的用户时,我遇到了此错误.
With this code, when I'm trying to get users of a task, I'm getting this error.
找不到基本表或视图:1146表'database_hosted_on_host1_server.task_user'不存在.
Base table or view not found: 1146 Table 'database_hosted_on_host1_server.task_user' doesn't exist.
在两个代码中,关系表都被分配了host1连接(相关表即用户的连接).但是它存在于host2连接中.而且我的默认连接是host2.
In both code, relational table is getting assigned with host1 connection (connection of related table i.e, users). But it exists in host2 connection. And also my default connection is host2.
我几乎花了太多时间来解决这个问题.但是没有任何办法.如果有人知道答案,将不胜感激.
I have almost spent too much time to resolve this. But didn't get any way. If anyone knows the answer, it will be appreciated.