【问题标题】:Laravel Many To Many Pivot Table different DatabaseLaravel 多对多数据透视表不同的数据库
【发布时间】:2018-02-02 13:15:00
【问题描述】:

Laravel 5.5

我有两个模型,UserConversation

用户到对话是多对多关系(双向)。

我的表结构如下:

conversation is on database_1
conversation_user is on database_1
user is on database_2

在 App\Conversation.php 内:

protected $connection = 'database_1';
protected $table = 'conversations';
public function users()
{
    return $this->belongsToMany("App\User");
}

App\User.php 内部:

protected $connection = 'database_2';
protected $table = 'users';
public function conversations()
{
    return $this->belongsToMany("App\Conversation");
}

所有这些都在同一台服务器上,但有没有办法让它工作?

在 Conversation 上查询关系以获取用户时,它正在寻找 database_2.conversation_user 而不是 database_1.conversation_user

所以本质上,我需要说Pivot表位于database_1,有没有办法做到这一点?

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    解决此问题的一种方法是使用查询构建器来创建关系。在您的用户模型中尝试:

    public function conversations()
    {
        return DB::connection('db1_connection_name')->table('conversation_user')->where('user_id', $this->id)->get();
    }
    

    显然,您也可以在关系中为连接添加前缀:

    public function conversations() {
        return $this->belongsToMany(User::class, env('DB_CONNECTION_1').'.conversation_user', 'user_id', 'conversation_id');
     }
    

    【讨论】:

    • 行得通!还发现在关系定义中,您可以像这样提供 database_name.table_name:return $this->belongsToMany("App\User", "database_1.conversation_user");
    猜你喜欢
    • 2017-04-11
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 2019-03-25
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多