Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ChrisMcG's avatar

HasManyThrough Relationship

Hi All,

I'm trying to setup a HasManyThrough relationship where NONE of the primary keys are named 'id' in the database, i've specified the foreignkeys in the relationship but in the WHERE clause generated it will still refer to a column named '.id' in an AND join and doesn't seem to take the foreign key supplied (it does everywhere else...) Any ideas? I can fix by renaming field in the DB but just curious if I'm missing something?

Relationship:

public function images() {

    return $this->hasManyThrough(
        Image::class,
        ActivityImage::class,
        'fld_activityId', // Foreign key on the activityImage table...
        'fld_id', // Foreign key on the images table...
        'fld_id', // Local key on the activity table...
        'fld_imageId' // Local key on the activityImage table...
    );
}

generated sql... select tbl_image.*, tbl_activityImage.fld_activityId as laravel_through_key from tbl_image inner join tbl_activityImage on tbl_activityImage.fld_imageId = tbl_image.fld_id where tbl_activityImage.fld_activityId = 364 and (tbl_image.id like % 45 %) order by tbl_image.fld_id desc limit 6 offset 0

You'll see in the where clause tbl_image.id is referenced?? Is this just a glitch and I can't override?

Many Thanks

Chris

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

I assume you are referring to this? tbl_image.id like % 45 %

A hasManyThrough() does not use LIKE so this is from some other code of yours.. Show the query code. Or if its a global scope, show that

ChrisMcG's avatar

@Sinnbeck Bingo... I'm using it with Nova and in the Nova Resource 'id' is used automatically in the search declaration...

public static $search = [ 'id', ];

Cheers for pointing me in right direction, all fixed...

Please or to participate in this conversation.