staudenmeir / belongs-to-through

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

Issue with custom foreign keys #64

Closed sarik-k closed 2 years ago

sarik-k commented 2 years ago

I have a hasManyThrough relationship like this:

user → has many → post → has many → comments

The post has a column added_by which references id on users.

My relationships are like this:

User.php

 public function comments()
    {
        return $this->hasManyThrough(Comment::class, Post::class, 'added_by');
    }

Comment.php

public function user()
    {
        return $this->belongsToThrough('App\Models\User', 'App\Models\Post', null, '', ['App\Models\Post' => 'added_by']);
    }

However when running $comment->user, I'm getting the following error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.user_id' in 'on clause' (SQL: select `users`.*, (select count(*) from `posts` where `users`.`id` = `posts`.`added_by`) as `post_count`, (select count(*) from `comments` inner join `posts` on `posts`.`id` = `comments`.`post_id` where `users`.`id` = `posts`.`added_by`) as `comment_count` from `users` 
inner join `posts` on `posts`.`user_id` = `users`.`id` where `posts`.`id` is null limit 1)

It looks like its still trying to find user_id column in posts table in the last inner join statement instead of added_by.

staudenmeir commented 2 years ago

Use the model that the custom foreign key is referencing (instead of the model/table the key is in):

public function user()
    {
        return $this->belongsToThrough(
            'App\Models\User',
            'App\Models\Post',
            null,
            '',
            ['App\Models\User' => 'added_by']
         );   ^^^^^^^^^^^^^^^
    }