请教 Lumen 的多对多关系中,涉及跨库问题的时候,中间表指定 connection 无效的问题

数据库结构

users 用户表, 在jcusercenter数据库

exams 考试表,在wgzr数据库

exam_user中间表,为一场考试指定参考学生 在wgzr数据库

模型

exams表模型

class Exam extends Model
{
    protected $connection = 'mysql';

    public function students()
    {
      return $this->belongsToMany(User::class)->using(ExamUser::class);
    }
}

users表在另一个数据库

class User extends Model
{
  protected $connection = 'user_center';

  protected $table='productimportuser';
}

中间表

class ExamUser extends Pivot
{
    protected $connection = 'mysql';
}

然后当我需要指定参考学生的时候,执行代码: $exam->students()->sync($request->student_ids);出现下面的错误.

Base table or view not found: 1146 Table 'jcusercenter.exam_user' doesn't exist (SQL: select * from `exam_user` where `exam_id` = 12)

当时遇到问题,查到类似的回答说是让创建中间表模型,在模型里面指定$connection,我现在也是这么做的.但是查询的时候还是会在users表所在的库中查询中间表.

想请教各位有没有什么解决方法?

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
bigliang_iOS
最佳答案

发现给中间表指定数据库就可以了. :sweat_smile:

public function students()
{
    return $this->belongsToMany(User::class, env('DB_DATABASE').'.exam_user', 'exam_id', 'user_id');
}
4年前 评论
qq907274532 3年前
讨论数量: 4
bigliang_iOS

:joy: 放弃了. 不用sync方法了,直接把数据插入中间表了.

DB::table('exam_user')->insert($exam_user_array);
4年前 评论
lochpure

其实吧,问题可以简单些,比如:为什么不放在同一个数据库呢 :relaxed:

4年前 评论
bigliang_iOS (楼主) 4年前
bigliang_iOS

发现给中间表指定数据库就可以了. :sweat_smile:

public function students()
{
    return $this->belongsToMany(User::class, env('DB_DATABASE').'.exam_user', 'exam_id', 'user_id');
}
4年前 评论
qq907274532 3年前

没有效果啊,还是错误的

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!