dongyou9373 2018-02-02 13:15
浏览 44
已采纳

Laravel很多很多数据透视表不同的数据库

Laravel 5.5

I've got two models, User and Conversation

User to Conversations is a many to many relationship (both ways).

My table structure is as follows:

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

Inside App\Conversation.php:

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

Inside App\User.php:

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

All of this is on the same server but is there a way to have this working or not ?

When querying the relationship on Conversation to get users, it's looking for database_2.conversation_user instead of database_1.conversation_user

So in essence, I need to say that the Pivot table is located in database_1, is there a way to do this?

  • 写回答

1条回答 默认 最新

  • doutang2017 2018-02-02 13:21
    关注

    One way to work around this is using the query builder to create the relationship. In your User model try:

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

    Apparently you can prefix the connection in a relationship also:

    public function conversations() {
        return $this->belongsToMany(User::class, env('DB_CONNECTION_1').'.conversation_user', 'user_id', 'conversation_id');
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?