Maruu's avatar
Level 38

Conditional Eager Loading in a Multi-Table Relationship

I am working with a database that includes four related tables:

  • campaigns
  • users
  • corporation_users
  • corporations

The relationships between these tables are as follows:

  • campaigns and users have a many-to-one relationship (n <=> 1).
  • users and corporation_users have a one-to-many relationship (1 <=> n).
  • corporation_users and corporations have a many-to-one relationship (n <=> 1).
  • Additionally, campaigns and corporations have a one-to-many relationship (n <=> 1).

I am attempting to retrieve campaigns with all related entities eagerly loaded. My current Laravel Eloquent query looks like this:

Campaign::with([
    'user',
    'user.corporation_users',
    'corporation'
])->get();

However, I need to modify this query so that it only retrieves corporation_users that are related to the corporation associated with each campaign.

How can I add a condition to user.corporation_users in this query to achieve this?

0 likes
3 replies
DhPandya's avatar

Use a callback function like below.

Campaign::with([
    'user',
    'user.corporation_users' => function ($query) {
        $query->has('corporation');
    },
    'corporation'
])->get();
1 like
Maruu's avatar
Level 38

@DhPandya Thank you for your reply! However, can this callback function retrieve corporation_users that are related to the campaign.corporation?

Please or to participate in this conversation.