One solution to this problem is to define a custom relationship method on the Company model that uses a nested eager loading query to retrieve the related User models through the License model. Here's an example implementation:
class Company extends Model
{
public function users()
{
return $this->hasManyThrough(
User::class,
License::class,
'company_id', // Foreign key on licenses table
'id', // Local key on users table
'id', // Local key on licenses table
'user_id' // Foreign key on users table
)->with('licenses');
}
}
This method defines a hasManyThrough relationship between the Company and User models, using the License model as an intermediate model. The foreign key on the License model that references the Company model is 'company_id', and the foreign key on the User model that references the License model is 'user_id'.
The key to making this work is the 'with' method call at the end of the relationship definition. This tells Laravel to eager load the related License models for each User model that is retrieved through the hasManyThrough relationship. This allows us to access the Company model for each License model, completing the mixed relationship.
With this relationship defined, you can now retrieve all the User models related to a Company model like this:
$company = Company::find(1);
$users = $company->users;
This will return a collection of User models, each with their related License models and the Company model that owns those licenses.