【问题标题】:Laravel polimorphic relation for multiple databases多个数据库的 Laravel 多态关系
【发布时间】:2018-11-08 05:42:27
【问题描述】:

我正在尝试在两个数据库表之间建立多态关系。

数据库1:销售报告 数据库2:线程连接

在数据库 1 上的 SaleReport 下

public function relates(){
    return $this->morphMany(ThreadConnection::class, 'relation');
}

在数据库 2 的 ThreadConnection 上

public function relation(){
    return $this->morphTo();
}

但是当我试图得到这样的关系时

$salereport = App\SaleReport::find(1);
$salereport->relates


Illuminate/Database/QueryException with message 'SQLSTATE[42S02]: 
Base table or view not found: 1146 Table 'database1.thread_connections'
doesn't exist (SQL: select * from `thread_connections` where 
`thread_connections`.`relation_id` = 484694 and 
`thread_connections`.`relation_id` is not null and 
`thread_connections`.`relation_type` = App/SaleReport)'

我也尝试过将数据库连接定义到ThreadConnection中

$this->setConnection('database2')->morphTo();

但这也不起作用!

任何建议都会被采纳

【问题讨论】:

  • 您是否尝试设置受保护的 $connection = 'database2';在 ThreadConnection 模型中?
  • 我认为这里已经回答了您要查找的内容:stackoverflow.com/questions/25142968/…
  • 嗨@koalaok,谢谢,是的,我已经在模型中添加了 protected $connection = 'db1/db2' 属于数据库,并且表名 protected $table = 'table_names' 和这就像一个魅力,它真的很容易在两个具有多态关系的数据库之间建立关系。

标签: laravel polymorphism relation


【解决方案1】:

正如我之前在评论中所说,

读取错误:

Base table or view not found: 1146 Table 'database1.thread_connections'

意思是 Laravel 在 database1 连接中查找模型 ThreadConnection(database1 应该是默认连接,如果模型引用另一个连接,则应该显式设置)

在ThreadConnection中添加:

 protected $connection = 'database2';

将解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 2021-09-05
    • 2017-02-28
    • 2020-08-04
    • 2019-07-16
    • 1970-01-01
    • 2016-06-03
    • 2016-01-26
    相关资源
    最近更新 更多