Skip to content
Advertisement

Laravel HasMany across multiple connections

I want to retrieve Offers related to Offer on a second table offer_related because I can’t change the schema of the Offer table.

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.

  • database containing offers henceforth known as immutable
  • database containing offer_related henceforth known as mutable

Example schema is as follows

JavaScript

I’m assuming it’d be a belongsToMany relationship, but I can’t seem to get it right.

JavaScript

I’ve also tried to manually build out a belongsToMany relationship with a custom query with no success.

I’d like to be able to call

JavaScript

Advertisement

Answer

Change the relationship to:

JavaScript

Your original query was trying to establish a relationship without using the relation table (offer_related). That is the problem.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement