Even if somebody could point me in the right direction that would be very helpful :)
hasOneThrough where two models are the same table
Here's a brief summary of my models that I want to connect through a hasOneThrough relationship:
- User with
$user->role === 'agency'and$user->id === 1 - User with
$user->role === 'family'and$user->agency_id === 1 - Application with
$application->family_id === 2(or whatever the family id is)
A family user owns an application. An agency owns a family user. I'd like to be able to have an application object and call ->agency on it. This would be a hasOneThrough the family user that owns the application.
It sounds like this isn't possible because two of the models use the same table. Is that accurate?
Is it possible to construct a relationship like this via the query builder? Where i can get the agency by calling $application->agency instead of $application->agency() ?
A related issue
As a side note, I seem to be running into issues where, in an Application method, the family or agency methods are null. Does that have something to do with the model not being eager loaded?
For example, here's a method inside the Application model:
public function setApproved()
{
if (!$this->submitted_at) {
$this->submitted_at = now();
}
$this->approved_at = now();
$this->save();
Mail::to($this->family)
->cc($this->agency)
->send(new ApplicationApproved(URL::to($this->path()))
);
return $this->approved_at;
}
I've found that the $this->agency line in the Mail::to call doesn't always work. If I add $this->agency()->get(), then it seems to work. What's the technical reason for this just so I can understand what's going on better? Should I be making a database query for the family and agency within this method instead of relying on Eloquent to build these relationships?
Maybe more likely it's because my hacked together hasOneThrough for the agency is currently this:
public function agency()
{
return $this->family->agency();
}
While the family is what it should be:
public function family()
{
return $this->belongsTo(User::class, 'family_id');
}
If it helps, I first noticed this issue when writing tests. I didn't see it happen in real-world use yet.
Please or to participate in this conversation.