【问题标题】:Get relational data of many to many relationship with multiple database connection通过多个数据库连接获取多对多关系的关系数据
【发布时间】:2018-08-02 13:46:02
【问题描述】:
  • Laravel 版本:5.5。
  • PHP 版本:">=7.0.0",
  • 数据库驱动程序和版本:MySQL

说明:

我正在处理具有不同架构的多个数据库连接。 host1host2。我的默认数据库连接是 host2。 我的项目有两张桌子。用户存在于host1,任务存在于host2。

两个表上都有多对多关系。此关系的数据透视表是 task_users,它存在于 host2 上。

我的模型文件在这里。

用户.php

class User extends Authenticatable
{

   protected $connection = 'host1';

   public function tasks()
   {
       return $this->belongsToMany(Task::class, 'task_users', 'user_id', 'task_id');
   }
}

任务.php

class Task extends Model
{
    protected $connection = 'host2';

    public function users()
    {
        return $this->belongsToMany(User::class, 'task_users', 'task_id', 'user_id');
    }
}

复制步骤:

这是我想要做的

$task = Task::find($taskId); $task->users;

使用此模型文件,当我尝试获取任务的用户时,我会收到此错误。

Illuminate\Database\QueryException with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: the "task_user" 关系不存在

但是如果我像这样做相反的事情:

$user = User::find($userId); $user->task; 一切顺利。

我几乎花了太多时间来解决这个问题。但无论如何都没有得到。我不知道这是 laravel 中的问题,不支持,或者我做错了。

【问题讨论】:

标签: laravel eloquent many-to-many relationship laravel-eloquent


【解决方案1】:

指定连接

public function users()
{
    return $this->belongsToMany(User::class, 'host2.task_users', 'task_id', 'user_id');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    相关资源
    最近更新 更多