问题描述
我想在第二张表offer_related
上检索与Offer
相关的Offer
,因为我无法更改Offer
表的架构.
I want to retrieve Offer
s related to Offer
on a second table offer_related
because I can't change the schema of the Offer
table.
我在不同的连接上有两个数据库,一个在offers
上,另一个在offer_related
上.
I have two databases on different connections, offers
on one, and offer_related
on another.
为了争辩,在示例中,为清楚起见,我将为数据库命名的方式如下:哪些可以更改,哪些不能更改.
For the sake of argument, I'm going to name databases as follows for clarity in my examples with regards to which can change and which can't.
- 包含
- 数据库此后称为
immutable
包含 - 数据库此后称为
mutable
offers
的offer_related
的- database containing
offers
henceforth known asimmutable
- database containing
offer_related
henceforth known asmutable
示例架构如下
connection1.mutable.offer_related
offer_id | related_offer_id
---------------------------
1 | 2
1 | 3
connection2.immutable.offers
id | name
---------------------------
1 | foo
2 | bar
3 | baz
我假设这将是一个belongsToMany关系,但是我似乎无法正确理解.
I'm assuming it'd be a belongsToMany relationship, but I can't seem to get it right.
return $this->belongsToMany(Offer::class, 'immutable.offer', 'id');
// Syntax error or access violation: 1066 Not unique table/alias: 'offer'
我还尝试过使用自定义查询手动建立一个AboutToMany关系,但没有成功.
I've also tried to manually build out a belongsToMany relationship with a custom query with no success.
我想可以打电话
Offer::find(1)->related; // Offer(2), Offer(3)
推荐答案
将关系更改为:
return $this->belongsToMany(Offer::class, 'mutable.offer_related',
'offer_id', 'related_offer_id');
您的原始查询尝试建立关系而不使用关系表(offer_related).那是问题.
Your original query was trying to establish a relationship without using the relation table (offer_related). That is the problem.
这篇关于Laravel HasMany跨多个连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!