staudenmeir / belongs-to-through

Laravel Eloquent BelongsToThrough relationships
MIT License
1.15k stars 88 forks source link

I might be doing something wrong, a little help? #103

Closed maxacarvalho closed 1 month ago

maxacarvalho commented 1 month ago

Hi, thanks for your nice package. I think I'm doing something wrong, I can't make it work with my use case.

What I have is:

nick_comunica_aws_sms_usage_reports

column
id
notification_id (fk nick_comunica_notifications)

nick_comunica_notifications

column
id
client_id (fk clients)
message

clients

column
id
name

So, an entry in the nick_comunica_aws_sms_usage_reports table belongs to an entry in the nick_comunica_notifications table which belongs to an entry in the clients table.

In my AwsSmsUsageReport model I added the trait Znck\Eloquent\Traits\BelongsToThrough and the following method:


    public function client(): BelongsToThrough
    {
        return $this->belongsToThrough(
            related: Client::class,
            through: Notification::class,
        );
    }

Then I instantiate a record from the AwsSmsUsageReport model:

$report = AwsSmsUsageReport::query()->find(15);

When I call the client relationship I get a null response back.
By inspecting the SQL query that's running I can see that the query misses the notification_id in the call to the clients table:

SELECT
  *
FROM
  `nick_comunica_aws_sms_usage_reports`
WHERE
  `nick_comunica_aws_sms_usage_reports`.`id` = 15
LIMIT
  1
SELECT
  `clients`.*
FROM
  `clients`
  INNER JOIN `nick_comunica_notifications` ON `nick_comunica_notifications`.`client_id` = `clients`.`id`
WHERE
  `nick_comunica_notifications`.`id` IS NULL
LIMIT
  1

Any help?

Thank you!

staudenmeir commented 1 month ago

Hi @maxacarvalho,

When I call the client relationship I get a null response back

What does your code look like?

maxacarvalho commented 1 month ago

Hi @staudenmeir Thanks for your speedy reply. But I just realised that I can get it to work with the Laravel standard hasOneThrough and hasManyThrough relationships 🤦🏽

Here's the solution:

AwsSmsUsageReport model:


    public function client(): HasOneThrough
    {
        return $this->hasOneThrough(
            Client::class,
            Notification::class,
            'id',
            'id',
            'notification_id',
            'client_id'
        );
    }

Client model:


    public function awsSmsUsageReports()
    {
        return $this->hasManyThrough(
            AwsSmsUsageReport::class,
            Notification::class,
        );
    }