gpt4 book ai didi

php - Laravel 多对多数据透视表不同的数据库

转载 作者:可可西里 更新时间:2023-11-01 00:39:35 24 4
gpt4 key购买 nike

拉拉维尔 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

所以本质上,我需要说数据透视表位于 database_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');
}

关于php - Laravel 多对多数据透视表不同的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48583500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com